<template>
  <div class="medical-workstation">
    <div class="main-container">
      <!-- 左侧边栏 -->
      <el-aside width="18%" class="modern-sidebar">
        <div class="sidebar-container">
          <!-- 待诊病人表格 (30%高度) -->
          <div class="waiting-table">
            <div class="table-header">
              <span class="title">待诊病人 ({{ tableData1.length }})人</span>
              <el-button size="mini" type="primary" @click="handleRefreshTable">刷新</el-button>
            </div>
            <el-table
                size="mini"
                border
                ref="tableData1"
                :data="tableData1"
                class="sticky-header-table"
                @row-contextmenu="handleReceptionClick"
                @row-click="handleClickRow"
            >
              <el-table-column
                  v-for="(col, inx) in tableRows1"
                  :key="inx"
                  :type="col.type"
                  :prop="col.prop"
                  :label="col.name"
                  :render-header="labelHead"
                  align="center"
                  :min-width="getColumnWidth(col.label,col.prop,tableData1)"
              />
            </el-table>
            <div v-show="showReception" class="context-menu"
                 :style="{left: contextMenuLeft + 'px', top: contextMenuTop + 'px'}">
              <div class="menu-item" @click="handleMenuClick(1)">接诊</div>
            </div>
          </div>

          <!-- 接诊病人表格 (70%高度) -->
          <div class="reception-table">
            <div class="table-header">
              <span class="title">接诊病人 ({{ tableData2.length }})人</span>
              <el-button size="mini" type="primary" @click="handleFastReceptionClick">快速接诊</el-button>
            </div>
            <el-table
                size="mini"
                border
                :data="tableData2"
                class="sticky-header-table"
                @row-contextmenu="handleCancelReceptionClick"
                @row-click="handleClickReceptionRow"
            >
              <el-table-column
                  v-for="(col, inx) in tableRows2"
                  :key="inx"
                  :type="col.type"
                  :prop="col.prop"
                  :label="col.name"
                  :render-header="labelHead"
                  align="center"
                  :min-width="getColumnWidth(col.label,col.prop,tableData2)"
              >
                <template #default="{ row }">
                  {{ safeGetMappedValue(col, row) }}
                </template>
              </el-table-column>
            </el-table>
            <!-- 右键菜单 -->
            <div
                v-show="showCancelReception"
                class="context-menu"
                :style="{left: contextMenuLeft + 'px', top: contextMenuTop + 'px'}"
            >
              <div class="menu-item" @click="handleMenuClick(3)">完成接诊</div>
              <div class="menu-item" @click="handleMenuClick(2)">取消接诊</div>
            </div>
          </div>
        </div>
      </el-aside>

      <!-- 主内容区 -->
      <el-main class="content">
        <div class="content-header">
          <div class="header-content">
            <span class="clinic-title">门诊</span>
            <span class="visit-count" v-if="patientForm.repeated">第{{ patientForm.repeated }}次就诊</span>
          </div>
          <div class="header-actions">
            <el-button size="mini" type="primary" @click="handleOpenDrawer('medicalRecord')"
                       :disabled="this.patientForm.patId === ''">病历文书
            </el-button>
            <el-button size="mini" type="primary" @click="handleOpenDrawer('outpatientsDiagnosis')"
                       :disabled="this.patientForm.patId === ''">门诊诊疗
            </el-button>

            <el-button size="mini" type="primary" @click="handleRecordingModalData"
                       :disabled="this.patientForm.patId === ''">录音记录
            </el-button>
            <el-button size="mini" type="primary" @click="handleSavenData">
              就诊记录
            </el-button>
          </div>
        </div>

        <div class="seedoctorMedical">
          <div class="medical-header">
            <span class="clinic-title">病历</span>
            <div class="header-actions">
              <el-button
                  style="padding: 7px 8px;"
                  size="mini"
                  @click.stop="showRecordingModal = true"
                  :disabled="this.patientForm.patId === ''"
              >
                <div style="display: flex; align-items: center;">
                  <i class="el-icon-microphone" style="font-size: 14px; color: #E6A23C;margin: 0"></i>
                  <span style="font-size: 12px;">{{ isRecording ? '录制中' : '病历录音' }}</span>
                </div>
              </el-button>
            </div>
          </div>
          <el-descriptions class="medical-history" :column="1" size="mini" border>
            <el-descriptions-item>
              <template slot="label">
                <div style="text-align: center; width: 100%">主诉</div>
              </template>
              <el-input
                  size="mini"
                  v-if="!showPatientTellSelect"
                  data-field="patientTell"
                  placeholder="单击选择诊断"
                  v-model="addSeedoctorForm.patientTell"
                  @dblclick.native="switchToSelect(1)"
                  @focus="handleGetMedicalKeywordList(1)"
                  @blur="choosePatientTell"
                  style="width: 100%"
                  :border="false"
                  class="cell-input"
              ></el-input>
              <el-select
                  v-else
                  size="mini"
                  ref="showPatientTellSelect"
                  v-model="addSeedoctorForm.patientTell"
                  filterable
                  clearable
                  allow-create
                  placeholder="选择或输入诊断"
                  style="width: 100%; font-size: 12px;"
                  @blur="handleBlur"
                  @change="choosePatientTell">
                <el-option
                    v-for="item in complainTemplateOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.label">
                      <span style="float: right" v-if="permissionsArr.includes('system:complaintemplate:edit')">
                        <el-button size="mini" type="primary" plain @click="handleEditAllTemplate(1,item)"
                                   style="margin-left: 6px; padding: 4px;">修改</el-button>
                      </span>
                  <span style="float: right; color: #8492a6; font-size: 12px;">{{ item.label }}</span>
                </el-option>
                <el-option :value="undefined" disabled style="cursor: pointer"
                           v-if="permissionsArr.includes('system:complaintemplate:add')">
                  <el-button type="text" @click="handleAddAllTemplate(1)" style="padding: 0;">
                    <i class="el-icon-plus" style="font-weight: bold"></i> 新增主诉模板
                  </el-button>
                </el-option>
              </el-select>
            </el-descriptions-item>

            <el-descriptions-item>
              <template slot="label">
                <div style="text-align: center; width: 100%">现病史</div>
              </template>
              <el-input
                  v-if="!showNowHistorySelect"
                  data-field="nowHistory"
                  placeholder="单击选择诊断"
                  v-model="addSeedoctorForm.nowHistory"
                  @focus="handleGetMedicalKeywordList(2)"
                  @dblclick.native="switchToSelect(2)"
                  @blur="chooseNowHistory"
                  style="width: 100%"
                  :border="false"
                  size="mini"
                  class="cell-input"
              ></el-input>
              <el-select
                  v-else
                  size="mini"
                  ref="showNowHistorySelect"
                  v-model="addSeedoctorForm.nowHistory"
                  filterable
                  clearable
                  allow-create
                  placeholder="选择或输入诊断"
                  style="width: 100%; font-size: 12px;"
                  @blur="handleBlur"
                  @change="chooseNowHistory">
                <el-option
                    v-for="item in nowHistoryTemplateOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.label">
                      <span style="float: right" v-if="permissionsArr.includes('system:nowsickness:edit')">
                        <el-button size="mini" type="primary" plain @click="handleEditAllTemplate(2,item)"
                                   style="margin-left: 6px; padding: 4px;">修改</el-button>
                      </span>
                  <span style="float: right; color: #8492a6; font-size: 12px;">{{ item.label }}</span>
                </el-option>
                <el-option :value="undefined" disabled style="cursor: pointer"
                           v-if="permissionsArr.includes('system:nowsickness:add')">
                  <el-button type="text" @click="handleAddAllTemplate(2)" style="padding: 0;">
                    <i class="el-icon-plus" style="font-weight: bold"></i> 新增现病史模板
                  </el-button>
                </el-option>
              </el-select>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <div style="text-align: center; width: 100%">既往史</div>
              </template>
              <el-input
                  v-if="!showBeforeHistorySelect"
                  data-field="beforeHistory"
                  placeholder="单击选择诊断"
                  v-model="addSeedoctorForm.beforeHistory"
                  @focus="handleGetMedicalKeywordList(3)"
                  @dblclick.native="switchToSelect(3)"
                  @blur="chooseBeforeHistory"
                  style="width: 100%"
                  :border="false"
                  size="mini"
                  class="cell-input"
              ></el-input>
              <el-select
                  v-else
                  size="mini"
                  ref="showBeforeHistorySelect"
                  v-model="addSeedoctorForm.beforeHistory"
                  filterable
                  clearable
                  allow-create
                  placeholder="选择或输入诊断"
                  style="width: 100%; font-size: 12px;"
                  @blur="handleBlur"
                  @change="chooseBeforeHistory">
                <el-option
                    v-for="item in beforeHistoryTemplateOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.label">
                      <span style="float: right" v-if="permissionsArr.includes('system:history:edit')">
                        <el-button size="mini" type="primary" plain @click="handleEditAllTemplate(3,item)"
                                   style="margin-left: 6px; padding: 4px;">修改</el-button>
                      </span>
                  <span style="float: right; color: #8492a6; font-size: 12px;">{{ item.label }}</span>
                </el-option>
                <el-option :value="undefined" disabled style="cursor: pointer"
                           v-if="permissionsArr.includes('system:history:add')">
                  <el-button type="text" @click="handleAddAllTemplate(3)" style="padding: 0;">
                    <i class="el-icon-plus" style="font-weight: bold"></i> 新增既往史模板
                  </el-button>
                </el-option>
              </el-select>

            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <div style="text-align: center; width: 100%">西医诊断</div>
              </template>
              <el-input
                  size="mini"
                  class="cell-input"
                  v-model="addSeedoctorForm.westernDiagnos"
                  placeholder="双击选择诊断"
                  readonly
                  clearable
                  style="width: 100%; font-size: 12px; padding-right: 30px;"
                  :autosize="{ minRows: 1, maxRows: 2 }"
                  @dblclick.native="getWesternDiagnosisData">
              </el-input>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <div style="text-align: center; width: 100%">中医诊断</div>
              </template>
              <el-input
                  size="mini"
                  class="cell-input"
                  v-model="addSeedoctorForm.chinaDiagnose"
                  placeholder="双击选择诊断"
                  readonly
                  clearable
                  style="width: 100%; font-size: 12px; padding-right: 30px;"
                  :autosize="{ minRows: 1, maxRows: 2 }"
                  @dblclick.native="getChinaDiagnosisOptions">
              </el-input>
            </el-descriptions-item>
          </el-descriptions>

          <div class="keywords-panel" v-if="keywordsVisible" @click.stop>
            <div class="keywords-content-expanded">
              <div v-for="group in keywordGroups[activeField]" :key="group.type" class="group-section">
                <div class="group-title">
                  {{ group.title }}
                </div>
                <div class="group-keywords">
                  <el-tag
                      v-for="(word, index) in group.keywords"
                      :key="index"
                      @click.native="addKeyword(word)"
                      class="keyword-tag"
                  >
                    {{ word }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>


        </div>

        <div class="seedoctorMedical">
          <div class="medical-header">
            <span class="clinic-title">处置项目</span>
            <div class="header-actions">
              <el-button
                  size="mini"
                  style="padding: 7px 8px;"
                  @click="handleShowDoctordisposeTabel1"
                  :disabled="this.patientForm.patId === ''"
              >
                <div style="display: flex; align-items: center;">
                  <i class="el-icon-edit-outline" style="font-size: 14px; color: #E6A23C;margin: 0"></i>
                  <span style="font-size: 12px;">处置项目</span>
                </div>
              </el-button>
            </div>
          </div>

          <!-- 一体化输入区域 -->
          <div style="border: 1px solid #DCDFE6; border-top: none; border-radius: 0 0 8px 8px; padding: 10px; position: relative;
           display: flex; align-items: center; flex-wrap: wrap;">
            <div style=" flex-grow: 1; display: flex; flex-wrap: wrap; align-items: center; gap: 5px;">
              <el-tag
                  closable
                  v-for="(item, index) in doctordisposeTableData"
                  :key="index"
                  effect="dark"
                  size="small"
                  :disable-transitions="true"
                  :hit="true"
                  @close="handleClearDisposeToTag(item)"
              >
                {{ item.costname + ': (频率' + item.exeFrquId + '次)' }}
              </el-tag>
            </div>
          </div>
        </div>

        <div class="seedoctorMedical">
          <div class="medical-header">
            <span class="clinic-title">
              <el-dropdown @command="handleCommand" trigger="click">
              <span class="el-dropdown-link">{{ DropDownedName }}<i class="el-icon-down"></i></span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="a">西药医嘱</el-dropdown-item>
                <el-dropdown-item command="b" divided>中药医嘱</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            </span>
            <el-popover
                placement="top-start"
                width="1000"
                trigger="click"
                v-model="showWestTable"
                popper-class="modern-medicine-popover"
                style="margin-left: 100px"
            >
              <el-input
                  v-if="DropDownedName === '西药医嘱'"
                  size="mini"
                  slot="reference"
                  v-model="medicineSearchQuery"
                  style="width: 500px;margin-left: 50px"
                  :placeholder="'输入西药名称搜索'"
                  clearable
                  @input="debouncedWestSearch"
                  @click.native="handleSearchWestMedicine()"
              >
                <el-select v-model="addWesternForm.rxType" slot="prepend" placeholder="请选择" style="width: 100px;">
                  <el-option
                      v-for="item in rxTypeOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-input>

              <el-input
                  v-else
                  size="mini"
                  slot="reference"
                  v-model="medicineSearchQuery"
                  style="width: 500px;margin-left: 50px;"
                  :placeholder="'输入中药名称搜索'"
                  clearable
                  @select="debouncedChinaSearch"
                  @click.native="handleSearchChinaMedicine()"
              >
                <el-input
                    v-model="addChinaForm.sdoseCnt"
                    slot="append"
                    size="small"
                    ref="dosageInput"
                    style="width: 130px"
                    placeholder="剂量"
                    @keyup.enter.native="handleDosageEnter"
                    @input="handleNumericInput"
                >
                  <template slot="append">g</template>
                </el-input>
              </el-input>
              <!-- 搜索表格内容 -->
              <div class="modern-table-wrapper">
                <el-table
                    :data="DropDownedName === '西药医嘱' ? pagedWestMedicineData : pagedChinaMedicineData"
                    style="width: 100%"
                    border
                    size="mini"
                    v-loading="loading"
                    :empty-text="searchTriggered ? '未找到相关药品' : '请在上方输入框输入搜索条件'"
                    highlight-current-row
                    @row-click="handleTableRowClick"
                    :max-height="500"
                    :row-class-name="tableRowClassName"
                >
                  <template #empty>
                    <div class="empty-state">
                      <i class="el-icon-search"></i>
                      <p>{{ searchTriggered ? '未找到匹配药品' : '请输入搜索条件' }}</p>
                    </div>
                  </template>

                  <el-table-column
                      v-for="(col, index) in (DropDownedName === '西药医嘱' ? tableRows11 : tableRows12)"
                      :key="`west_col_${index}`"
                      :type="col.type"
                      :prop="col.prop"
                      :label="col.name"
                      :render-header="labelHead"
                      align="center"
                      :min-width="getColumnWidth(col.label,col.prop,
                      DropDownedName === '西药医嘱' ? queryWestMedicineData : queryChinaMedicineData)"
                  >
                    <template #default="{ row }">
                      {{ safeGetMappedValue(col, row, 0) }}
                    </template>
                  </el-table-column>
                </el-table>

                <el-pagination
                    v-if="(DropDownedName === '西药医嘱' ? westPagination : chinaPagination).total > 0"
                    small
                    layout="prev, pager, next, jumper"
                    :total="(DropDownedName === '西药医嘱' ? westPagination : chinaPagination).total"
                    :page-size="(DropDownedName === '西药医嘱' ? westPagination : chinaPagination).pageSize"
                    :current-page="(DropDownedName === '西药医嘱' ? westPagination : chinaPagination).currentPage"
                    @current-change="DropDownedName === '西药医嘱' ? handleWestPageChange : handleChinaPageChange"
                    class="modern-pagination"
                />
              </div>

              <!-- 搜索输入框 -->

            </el-popover>
            <div class="header-actions">
              <el-button
                  size="mini"
                  style="padding: 7px 8px;"
                  @click="handleConfirmMedicalAdvice"
                  v-if="!isShowPrescription"
                  :disabled="this.patientForm.patId === ''"
              >
                <div style="display: flex; align-items: center;">
                  <i class="el-icon-edit-outline" style="font-size: 14px; color: #E6A23C;margin: 0"></i>
                  <span style="font-size: 12px;">提交医嘱</span>
                </div>
              </el-button>
            </div>
          </div>

          <!-- 一体化输入区域 -->
          <div>
            <div style=" flex-grow: 1; display: flex; flex-wrap: wrap; align-items: center; gap: 5px;margin: 0;
position: relative; width: 100%; overflow: hidden;" v-if="DropDownedName === '西药医嘱'">
              <el-table
                  size="mini"
f                  ref="westMedicineTableData"
                  style="width: 100% !important;margin: 0 !important;border-radius: 0 0 8px 8px;"
                  :data="westMedicineTableData"
                  border
                  highlight-current-row
                  row-key="id"
                  @selection-change="handleWestGroups"
                  @row-contextmenu="handleWestGroupsFixed"
                  @row-dblclick="handleShowDataDetail"
                  :class="{ 'disabled-table': isShowPrescription }"
              >
                <el-table-column
                    type="selection"
                    width="55"
                    align="center"
                ></el-table-column>
                <el-table-column label="操作" width="80" align="center">
                  <template slot-scope="scope">
                    <el-button
                        :disabled="isShowPrescription || scope.row.adviceId > 0"
                        size="mini"
                        type="text"
                        @click="removeWestMedicineTableData(scope.$index)"
                    >移除
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column v-for="(col, inx) in (DropDownedName === '西药医嘱' ? tableRows7 : tableRows12)"
                                 :key="inx" :type="col.type"
                                 :label="col.name" :render-header="labelHead" align="center"
                                 :width="col.prop === 'pacSpec' ? '200px' : null"
                                 :min-width="getColumnWidth(col.label,col.prop,westMedicineTableData)">
                  <template slot-scope="scope">
                    <template v-if="col.prop === 'usedfrquId'">
                      <el-select v-model="scope.row.usedfrquId" @change="getWestSdoseSum(scope.row)"
                                 filterable
                                 :disabled="scope.row._isFrquDisabled" placeholder="请选择">
                        <el-option v-for="item in medicationFrequencyOptions" :key="item.id" :label="item.label"
                                   :value="item.id"></el-option>
                      </el-select>
                    </template>

                    <template v-if="col.prop === 'medcWayId'">
                      <el-select v-model="scope.row.medcWayId"
                                 @change="(value) => isTransfusion(value, scope.row)" filterable
                                 :disabled="scope.row._isMedcWayDisabled"
                                 placeholder="请选择">
                        <el-option v-for="item in medicationWayOptions" :key="item.id" :label="item.label"
                                   :value="item.id"></el-option>
                      </el-select>
                    </template>

                    <template v-if="col.prop === 'dosaUnt'">
                      <el-select v-model="scope.row.dosaUnt" filterable clearable placeholder="请选择"
                                 :disabled="isShowPrescription">
                        <el-option v-for="item in dosaUntOptions" :key="item.id" :label="item.label"
                                   :value="item.id"></el-option>
                      </el-select>
                    </template>

                    <!--            <template v-if="col.prop === 'selfProe'">
                                  <el-select v-model="scope.row.selfProe" placeholder="请选择" @change="handleOwnedWest(scope.row)"
                                             :disabled="isShowPrescription">
                                    <el-option label="是" :value="1"></el-option>
                                    <el-option label="否" :value="0"></el-option>
                                  </el-select>
                                </template>-->

                    <template v-if="col.prop === 'prdCnt'">
                      <el-input v-model="scope.row[col.prop]" :class="{'special-input': col.prop === 'prdCnt'}"
                                @change="getWestSdoseSum(scope.row)" placeholder="请输入" disabled></el-input>
                    </template>

                    <template v-if="col.prop === 'sdoseCnt'">
                      <el-input v-model="scope.row[col.prop]" placeholder="请输入" :disabled="isShowPrescription"
                                :class="{'special-input': col.prop === 'sdoseCnt'}"
                                @change="getWestSdoseSum(scope.row)"></el-input>
                    </template>

                    <template v-if="col.prop === 'prdDays'">
                      <el-input v-model="scope.row[col.prop]" :class="{'special-input': col.prop === 'prdDays'}"
                                @change="getWestSdoseSum(scope.row)" placeholder="请输入"></el-input>
                    </template>

                    <template v-if="col.prop === 'remarks'">
                      <el-input type="textarea" v-model="scope.row[col.prop]" :class="{'hide-input-border': true}"
                                :disabled="isShowPrescription"
                                placeholder="请输入"></el-input>
                    </template>

                    <template v-if="col.prop === 'speed' && scope.row.medcWayType">
                      <el-input v-model="scope.row[col.prop]" :class="{'special-input': col.prop === 'speed'}"
                                :disabled="isShowPrescription" @input="handleGroupInfusionSync(scope.row)"
                                placeholder="请输入"></el-input>
                    </template>

                    <template v-else>
                      {{ safeGetMappedValue(col, scope.row) }}
                    </template>

                  </template>
                </el-table-column>
              </el-table>
              <div v-show="showWestGroupsClick" class="context-menu"
                   :style="{left: contextMenuLeft + 'px', top: contextMenuTop + 'px'}">
                <div class="menu-item" @click="handleMenuClick(5)">分组</div>
                <div class="menu-item" @click="handleMenuClick(6)">取消分组</div>
              </div>
            </div>

            <div v-else>
              <div class="medicine-whiteboard">
                <!-- 有数据时显示药品卡片 -->
                <template v-if="chinaMedicineTableData.length > 0">
                  <div
                      v-for="(item, index) in chinaMedicineTableData"
                      :key="index"
                      class="medicine-block"
                      @contextmenu="handleMedicineContextMenu(item, null, $event)"
                  >
                    <!-- 方法名显示在顶部 -->
                    <div v-show="item.methodName" class="medicine-method">制法/脚注:({{ item.methodName }})</div>

                    <!-- 药品名居中 -->
                    <div class="medicine-name">{{ item.drugName }}</div>

                    <!-- 剂量保持在底部 -->
                    <div class="medicine-dose" @click="openDoseDialog(item,index)">{{ item.sdoseCnt }}g</div>
                  </div>
                </template>

                <!-- 无数据时显示提示 -->
                <div v-else class="empty-tip">
                  <div class="tip-content">
                    <span>请在上方选择中药处方</span>
                  </div>
                </div>
              </div>
              <div
                  v-show="showChinaReception"
                  class="context-menu"
                  :style="{left: contextMenuLeft + 'px', top: contextMenuTop + 'px'}">
                <div class="menu-item" @click="handleMethodNote(chinaReceptionRowData, $event)">
                  <i class="el-icon-edit-outline"></i>
                  <span>制法/脚注</span>
                </div>
                <div class="menu-item" @click="handleClearMethod(chinaReceptionRowData, $event)">
                  <i class="el-icon-delete"></i>
                  <span>清除制法</span>
                </div>
                <div class="menu-item" @click="handleModifyDosage(chinaReceptionRowData)">
                  <i class="el-icon-edit"></i>
                  <span>修改用量</span>
                </div>
                <div class="menu-item" @click="handleDeleteMedicine(chinaReceptionRowData, $event)">
                  <i class="el-icon-close"></i>
                  <span>删除</span>
                </div>
              </div>
            </div>
          </div>
        </div>


        <div class="seedoctorMedical">
          <div class="medical-header">
            <span class="clinic-title">医嘱列表</span>
            <div class="header-actions">
            </div>
          </div>

          <!-- 一体化输入区域 -->
          <div style="border: 1px solid #DCDFE6; border-top: none; border-radius: 0 0 8px 8px; padding: 0; position: relative;
           display: flex; align-items: center; flex-wrap: wrap;overflow: auto;">
            <div style=" flex-grow: 1; display: flex; flex-wrap: wrap; align-items: center; gap: 5px;margin: 0;">
              <el-table
                  style="width: 100%;height: 100%"
                  :data="medicalAdviceData"
                  size="mini"
                  :row-class-name="setRowClassName"
                  class="compact-table"
                  show-summary
                  :summary-method="getPricSummary"
                  @row-contextmenu="handleAdviceRightClick"
                  @selection-change="handleSelectionActiveChange"
                  border>
                <el-table-column
                    type="selection"
                    width="60"
                    align="center"
                    :selectable="checkSelectable">
                </el-table-column>
                <el-table-column
                    v-for="(col, inx) in tableRows10"
                    :key="inx"
                    :type="col.type"
                    :prop="col.prop"
                    :label="col.name"
                    :render-header="labelHead"
                    :show-overflow-tooltip="false"
                    align="center"
                    :width="col.prop==='createTime' ? '150px' : col.prop==='content' ? '320px' : null"
                    :min-width="getColumnWidth(col.label,col.prop,medicalAdviceData)"
                    header-align="center"
                    class-name="compact-cell">
                  <template #default="{ row }">
                    <div v-if="col.prop === 'content'" style="white-space: pre-line; text-align: center;">
                      {{ formatPrescriptionContent(row.content) }}
                    </div>
                    <template v-else>
                      {{ safeGetMappedValue(col, row) }}
                    </template>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 右键菜单 -->
              <div v-show="showAdviceRightClick" class="context-menu"
                   :style="{left: contextMenuLeft + 'px', top: contextMenuTop + 'px'}">
                <div class="menu-item" @click="handleMenuClick(4)">删除</div>
                <div class="menu-item" @click="handleMenuClick(7)">批量删除</div>
              </div>
            </div>
          </div>
        </div>


      </el-main>
      <!-- 右侧边栏 -->
      <el-aside width="23%" class="right-sidebar">
        <div class="table-header" style="height: 28px; line-height: 28px; padding-left: 8px; font-weight: bold;">
          患者信息
        </div>

        <el-form
            :model="patientForm"
            :rules="patientFormDataRules"
            ref="patientFormDataRef"
            label-width="80px"
            size="mini"
            class="compact-form"
            style="padding: 8px;"
        >
          <!-- 基本信息区 -->


          <!-- 医疗信息区 -->
          <el-collapse v-model="activeCollapse">
            <el-collapse-item title="详细信息" name="seeDoctorData">
              <el-descriptions :column="1" size="mini" border>
                <el-descriptions-item>
                  <template slot="label">
                    <span class="label-text">健康ID</span>
                  </template>
                  <el-input
                      v-model="patientForm.patId"
                      prop="patId"
                      size="mini"
                      :disabled="isInputDisabled"
                      style="width: 100%;"
                  ></el-input>
                </el-descriptions-item>

                <el-descriptions-item label="姓名" style="width: 50%">
                  <el-input
                      v-model="patientForm.name"
                      prop="name"
                      size="mini"
                      :disabled="isInputDisabled"
                      style="width: 100%;"
                  ></el-input>
                </el-descriptions-item>

                <el-descriptions-item label="性别">
                  <el-select
                      v-model="patientForm.sex"
                      prop="sex"
                      size="mini"
                      style="width: 100%;"
                  >
                    <el-option label="男" value="1"></el-option>
                    <el-option label="女" value="2"></el-option>
                  </el-select>
                </el-descriptions-item>

                <el-descriptions-item label="证件">
                  <el-select v-model="patientForm.identityCard" size="mini" filterable clearable style="width: 100%"
                             prop="identityCard">
                    <el-option v-for="item in certypeOption" :key="item.id" :label="item.label"
                               :value="item.id"></el-option>
                  </el-select>
                  <el-input
                      v-model="patientForm.certno"
                      prop="certno"
                      @blur="certnoMonitor"
                      size="mini"
                      @clear="patientForm.ageYear = null;patientForm.ageMonth = null;patientForm.brdy = '';"
                      :maxlength="certLengthMap[patientForm.identityCard]"
                      show-word-limit
                  ></el-input>
                </el-descriptions-item>

                <el-descriptions-item label="电话">
                  <el-input
                      @blur="validateTel('tel')"
                      prop="tel"
                      v-model="patientForm.tel"
                      size="mini"
                      style="width: 100%;"
                  ></el-input>
                </el-descriptions-item>

<!--                <el-descriptions-item label="诊别">
                  <el-select
                      prop="repeated"
                      v-model="patientChooseForm.repeated"
                      size="mini"
                      style="width: 100%;"
                      :disabled="true"
                  >
                    <el-option v-for="item in repeatedOptions" :key="item.id" :label="item.label"
                               :value="item.id"></el-option>
                  </el-select>
                </el-descriptions-item>-->
              </el-descriptions>
            </el-collapse-item>

            <el-collapse-item title="医疗信息" name="medical">
              <el-descriptions :column="1" size="mini" border>
                <el-descriptions-item label="发病日期" class="relation-item">
                  <template slot="label">
                    <span class="no-wrap-label">发病日期</span>
                  </template>
                  <el-date-picker
                      v-model="patientForm.attackTime"
                      prop="attackTime"
                      type="date"
                      size="mini"
                      style="width: 100%;"
                      value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </el-descriptions-item>

                <el-descriptions-item label="过敏原">
                  <el-select
                      v-model="patientForm.aiseId"
                      prop="aiseId"
                      size="mini"
                      style="width: 100%;"
                      filterable
                      clearable
                  >
                    <el-option :value="undefined" disabled style="cursor: pointer"
                               v-if="permissionsArr.includes('system:aise:add')">
                      <el-button type="text" @click="handleAddOrEditAise" style="padding: 0;">
                        <i class="el-icon-plus" style="font-weight: bold"></i> 新增过敏原
                      </el-button>
                    </el-option>
                    <el-option v-for="item in aiseListOptions" :key="item.id" :label="item.label" :value="item.id">
                      <span style="color: #8492a6; font-size: 12px">{{ item.label }}</span>
                    </el-option>
                  </el-select>
                </el-descriptions-item>

                <el-descriptions-item label="血压">
                  <div style="display: flex; align-items: center;">
                    <el-input
                        ref="syspreRef"
                        prop="syspre"
                        v-model.number="patientForm.syspre"
                        size="mini"
                        :style="{ color: isSyspreInvalid ? 'red' : '' }"
                        placeholder="90-140"
                        style="width: 45%;"
                        @blur="validateBloodPressure"
                    ></el-input>
                    <span style="margin: 0 4px; font-size: 12px;">/</span>
                    <el-input
                        prop="diapre"
                        ref="diapreRef"
                        v-model.number="patientForm.diapre"
                        size="mini"
                        :style="{ color: isDiapreInvalid ? 'red' : '' }"
                        placeholder="60-90"
                        style="width: 45%;"
                        @blur="validateBloodPressure"
                    ></el-input>
                  </div>
                </el-descriptions-item>

                <el-descriptions-item label="血糖">
                  <div style="display: flex; align-items: center;">
                    <el-select
                        prop="bloodType"
                        v-model="patientForm.bloodType"
                        size="mini"
                        style="width: 100px; margin-right: 4px;"
                    >
                      <el-option
                          v-for="item in bloodTypeOptions"
                          :key="item.id"
                          :label="item.label"
                          :value="item.id"
                      >
                        <span style="color: #8492a6; font-size: 12px">{{ item.label }}</span>
                      </el-option>
                    </el-select>
                    <el-input
                        v-model.number="patientForm.bloodNumber"
                        ref="bloodNumberRef"
                        prop="bloodNumber"
                        size="mini"
                        style="width: 60px;"
                        :class="{ 'blood-error': isBloodNumberInvalid }"
                        :disabled="!patientForm.bloodType"
                        @blur="validateBloodNumber"
                    ></el-input>
                    <span style="font-size: 11px; margin-left: 4px;">mmol/L</span>
                  </div>
                </el-descriptions-item>

                <el-descriptions-item label="孕妇">
                  <el-checkbox
                      prop="pregnant"
                      v-model="patientForm.pregnant"
                      :true-label="1"
                      :false-label="0"
                      :disabled="patientForm.sex === '1' || patientForm.sex === null"
                  ></el-checkbox>
                </el-descriptions-item>
              </el-descriptions>
            </el-collapse-item>

            <el-collapse-item title="详细信息" name="details">
              <el-descriptions :column="1" size="mini" border>
                <el-descriptions-item label="出生日期">
                  <el-date-picker
                      prefix-icon="none"
                      v-model="patientForm.brdy"
                      prop="brdy"
                      type="date"
                      size="mini"
                      style="width: 100%;"
                      :disabled="patientForm.identityCard === 1"
                      :placeholder="patientForm.identityCard !== 1 ? '' : '证件自动计算'"
                      value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </el-descriptions-item>

                <el-descriptions-item label="年龄">
                  <div style="display: flex; align-items: center;">
                    <el-input
                        v-model="patientForm.ageYear"
                        size="mini"
                        prop="ageYear"
                        :disabled="patientForm.identityCard === 1"
                        style="width: 30%;"
                    ></el-input>
                    <span style="margin: 0 4px; font-size: 12px;">岁</span>
                    <el-input
                        v-model="patientForm.ageMonth"
                        size="mini"
                        prop="ageMonth"
                        :disabled="patientForm.identityCard === 1"
                        style="width: 30%;"
                    ></el-input>
                    <span style="margin-left: 4px; font-size: 12px;">月</span>
                  </div>
                </el-descriptions-item>

                <el-descriptions-item label="职业">
                  <el-select
                      v-model="patientForm.jobId"
                      size="mini"
                      prop="jobId"
                      style="width: 100%;"
                      filterable
                  >
                    <el-option v-for="item in jobOption" :key="item.id" :label="item.label"
                               :value="item.id"></el-option>
                  </el-select>
                </el-descriptions-item>

                <el-descriptions-item label="费别">
                  <el-select
                      v-model="patientForm.prhCostType"
                      size="mini"
                      prop="prhCostType"
                      style="width: 100%;"
                      filterable
                  >
                    <el-option v-for="item in prhCostOption" :key="item.id" :label="item.label" :value="item.id">
                      <span style="color: #8492a6; font-size: 12px">{{ item.label }}</span>
                    </el-option>
                  </el-select>
                </el-descriptions-item>

                <el-descriptions-item label="类型">
                  <el-select
                      v-model="patientForm.prhType"
                      size="mini"
                      prop="prhType"
                      style="width: 100%;"
                  >
                    <el-option v-for="item in prhTypeOption" :key="item.id" :label="item.label" :value="item.id">
                      <span style="color: #8492a6; font-size: 12px">{{ item.label }}</span>
                    </el-option>
                  </el-select>
                </el-descriptions-item>

                <el-descriptions-item label="合约单位">
                  <el-select v-model="patientForm.phrUnt" size="mini" prop="phrUnt"
                             style="width: 100%;" filterable>
                    <el-option :value="undefined" disabled style="cursor: pointer">
                      <el-button type="text" @click="handleSaveContractUnit" style="padding: 0;">
                        <i class="el-icon-plus" style="font-weight: bold"></i> 新增合约单位
                      </el-button>
                    </el-option>
                    <el-option v-for="item in contractUnitOption" :key="item.id" :label="item.label" :value="item.id">
                      <span style="float: left">{{ item.label }}</span>
                      <span style="float: right">
                  <el-button size="mini" type="primary" plain @click.stop="handleEditContractUnit(item)"
                             style="margin-left: 6px; padding: 4px;">修改</el-button>
                </span>
                    </el-option>
                  </el-select>
                </el-descriptions-item>

                <el-descriptions-item label="联系人">
                  <el-input
                      v-model="patientForm.conerName"
                      prop="conerName"
                      size="mini"
                      style="width: 100%;"
                  ></el-input>
                </el-descriptions-item>

                <el-descriptions-item label="联系电话">
                  <el-input
                      @blur="validateTel('conerTel')"
                      v-model="patientForm.conerTel"
                      prop="conerTel"
                      size="mini"
                      style="width: 100%;"
                  ></el-input>
                </el-descriptions-item>

                <el-descriptions-item label="联系人关系">
                  <el-select
                      prop="conerRltsId"
                      v-model="patientForm.conerRltsId"
                      size="mini"
                      style="width: 100%;"
                      filterable
                  >
                    <el-option v-for="item in rltsEntitiesOption" :key="item.id" :label="item.label" :value="item.id">
                      <span style="color: #8492a6; font-size: 12px">{{ item.label }}</span>
                    </el-option>
                  </el-select>
                </el-descriptions-item>

                <el-descriptions-item label="联系地址">
                  <el-cascader
                      size="mini"
                      ref="conerAddCodeArrRef"
                      prop="conerAddCodeArr"
                      :key="addressKey"
                      v-model="patientForm.conerAddCodeArr"
                      :props="addressProps"
                      :options="provinces"
                      @focus="initAddressData"
                      :placeholder="conerPleasett"
                      style="width: 100%; margin-bottom: 4px;"
                  />
                  <el-input
                      size="mini"
                      prop="conerAddName"
                      v-model="patientForm.conerAddName"
                      clearable
                      placeholder="详细地址"
                      style="width: 100%;"
                  />
                </el-descriptions-item>
              </el-descriptions>
            </el-collapse-item>
          </el-collapse>
        </el-form>
        <div style="margin-top: 40px; display: flex; justify-content: center; width: 100%;">
          <el-button
              type="primary"
              size="mini"
              style="padding: 5px 8px; margin: 0;"
              :loading="loading"
              @click="handleEditDocphr"
          >
            保存
            <el-tooltip content="若查询信息不对,可重新填写后点此按钮更改" placement="top">
              <i class="el-icon-question" style="margin-left: 3px; color: #fff;"></i>
            </el-tooltip>
          </el-button>
        </div>
      </el-aside>
    </div>

    <div class="drawer">
      <el-drawer
          :visible.sync="medicalRecord"
          :with-header="false"
          :modal="false"
          size="45%"
      >
        <div style="display: flex;flex-direction: column;align-items: center;
            justify-content: center;height: 100%;padding: 20px;">
          <div style="text-align: right; margin-bottom: 10px;">
            <el-button
                size="small"
                type="success"
                @click="printMedicalRecord"
                :disabled="patientForm.patId === ''"
            >
              打印病历
            </el-button>
          </div>

          <div class="preview-container" v-if="medicalRecordHTML" v-html="medicalRecordHTML"></div>
          <div class="no-data-message" v-else>
            <el-empty description="暂无数据,请联系管理员"></el-empty>
          </div>
        </div>
      </el-drawer>

      <el-drawer
          :visible.sync="outpatientsDiagnosis"
          :with-header="false"
          :modal="false"
          size="45%"
      >
        <div
            style="display: flex;align-items: center;height: 100px;padding: 20px; justify-content: center;margin-top: 50px;">
          <el-button
              size="small"
              type="primary"
              @click="printOutpatientsDiagnosisCombined"
              :disabled="patientForm.patId === ''"
          >
            打印病历
          </el-button>
          <el-button
              size="small"
              type="success"
              @click="printOutpatientsDerive"
              :disabled="patientForm.patId === ''"
          >
            导出Excel
          </el-button>
        </div>


        <!-- 使用 margin-top 让 div 下移 -->
        <div class="preview-container" v-if="outpatientsDiagnosisHTML" v-html="outpatientsDiagnosisHTML"
             style="margin-top: 50px;"></div>

        <div class="no-data-message" v-else style="margin-top: 20px;">
          <el-empty description="暂无数据,请联系管理员"></el-empty>
        </div>
      </el-drawer>
    </div>


    <div class="dialog">
      <el-dialog
          title="中药使用信息"
          :visible.sync="chinaMedicineUsageDialog"
          :before-close="handleCloseChinaTabel"
          width="25%"
          :close-on-click-modal="false"
      >
        <el-form :model="addChinaForm" label-width="120px" size="mini">
          <!-- 共付 -->
          <el-form-item label="共付:" style="margin-bottom: 12px">
            <el-input
                type="number"
                v-model.number="addChinaForm.tcmCnt"
                :min="1"
                @input="getChinaDosageSum"
                style="width: 200px"
            ></el-input>
          </el-form-item>

          <!-- 用法 -->
          <el-form-item label="用法:" style="margin-bottom: 12px">
            <el-select
                v-model="addChinaForm.tcmWayId"
                filterable
                clearable
                style="width: 200px"
            >
              <el-option
                  v-for="item in tcmwayOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>

          <!-- 给药方式 -->
          <el-form-item label="给药方式:" style="margin-bottom: 12px">
            <el-select
                v-model="addChinaForm.medcWayId"
                filterable
                style="width: 200px"
            >
              <el-option
                  v-for="item in chinaMedicationWayOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>

          <!-- 用药频率 -->
          <el-form-item label="用药频率:" style="margin-bottom: 12px">
            <el-select
                v-model="addChinaForm.usedfrquId"
                @focus="getMedicationFrequency"
                filterable
                clearable
                style="width: 200px"
            >
              <el-option
                  v-for="item in medicationFrequencyOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>



          <!-- 服法（双选择器复合） -->
          <el-form-item label="服法:" style="margin-bottom: 12px">
            <div style="display: flex; align-items: center; gap: 8px">
              <el-select
                  v-model="addChinaForm.takeMedicineWay1"
                  filterable
                  clearable
                  style="width: 96px"
              >
                <el-option
                    v-for="item in takeMedicineWayOptions1"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                />
              </el-select>
              <el-select
                  v-model="addChinaForm.takeMedicineWay2"
                  filterable
                  clearable
                  style="width: 96px"
              >
                <el-option
                    v-for="item in takeMedicineWayOptions2"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                />
              </el-select>
            </div>
          </el-form-item>

          <!-- 煎药方式 -->
          <el-form-item label="煎药方式:" style="margin-bottom: 12px">
            <el-select
                v-model="addChinaForm.extgType"
                filterable
                clearable
                style="width: 200px"
            >
              <el-option
                  v-for="item in extgTypeOption"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>

          <!-- 预算金额 -->
          <el-form-item label="预算金额:" style="margin-bottom: 12px">
            <el-input
                type="number"
                v-model.number="addChinaForm.predictMoney"
                :disabled="true"
                style="width: 200px"
            ></el-input>
          </el-form-item>
          <!-- 每次用量（复合输入框） -->
          <el-form-item label="每次:" style="margin-bottom: 12px">
            <div style="display: flex; align-items: center">
              <el-input
                  type="number"
                  ref="rxDosCnt"
                  :min="1"
                  v-model.number="addChinaForm.rxDosCnt"
                  style="width: 140px"
              ></el-input>
              <el-input
                  value="ML"
                  :disabled="true"
                  style="width: 30px; margin-left: 8px"
              ></el-input>
            </div>
          </el-form-item>

          <!-- 煎药用量（复合输入框） -->
          <el-form-item label="煎药用量:" style="margin-bottom: 12px">
            <div style="display: flex; align-items: center">
              <el-input
                  type="number"
                  ref="extgCnt"
                  v-model="addChinaForm.extgCnt"
                  :min="1"
                  style="width: 140px"
              ></el-input>
              <el-input
                  value="ML"
                  :disabled="true"
                  style="width: 30px; margin-left: 8px"
              ></el-input>
            </div>
          </el-form-item>
          <!-- 药品总量（复合输入框） -->
          <el-form-item label="药品总量:" style="margin-bottom: 12px">
            <div style="display: flex; align-items: center">
              <el-input
                  type="number"
                  v-model.number="addChinaForm.chinaMedicineSum"
                  :disabled="true"
                  style="width: 140px"
              ></el-input>
              <el-input
                  value="g"
                  :disabled="true"
                  style="width: 30px; margin-left: 8px"
              ></el-input>
            </div>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="handleCloseChinaTabel" size="mini">取 消</el-button>
          <el-button type="primary" @click="handleConfirmChina" size="mini">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="录音" :visible.sync="showRecordingModal" width="300px">
        <!-- 录制状态显示区域 -->
        <div class="recording-status" style="padding: 10px 0;">
          <div v-if="isRecording" class="wave-animation" style="height: 40px;"></div>
          <p v-if="isRecording" style="margin: 8px 0;">正在录制: {{ recordingTime }}</p>
          <p v-else style="margin: 8px 0;">请点击开始按钮开始录音</p>
          <div class="recording-buttons" style="display: flex; gap: 10px; margin-top: 10px;">
            <el-button
                size="mini"
                v-if="!isRecording"
                type="primary"
                @click="startRecording">
              开始录音
            </el-button>
            <el-button
                size="mini"
                v-else
                type="danger"
                @click="stopRecording">
              结束录音
            </el-button>
          </div>
        </div>
      </el-dialog>

      <el-dialog title="录音记录" :visible.sync="showRecordingModalData" style="margin: 0" width="70%" height="70vh">
        <el-container style="height: 100%; border: 1px solid #eee">
          <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
            <el-menu
                :default-openeds="['1']"
                @select="handleMenuSelect"
                v-model="activeIndex"
            >
              <el-submenu index="1">
                <template slot="title"><i class="el-icon-folder"></i>录音</template>
                <el-menu-item
                    v-for="(item, index) in recordingListOptions"
                    :key="item.index"
                    :index="item.index"
                    :data-audio-path="item.audioPath"
                    @click="handleAudioItemClick(item.audioPath)"
                >
                  {{ item.name }}
                </el-menu-item>
              </el-submenu>
            </el-menu>
          </el-aside>


          <el-container>
            <el-header
                style="text-align: left; font-size: 12px; padding: 0 20px; height: 60px; display: flex; align-items: center; justify-content: flex-start;">
              <div class="audio-player" v-if="currentAudioPath">
                <audio
                    ref="audioPlayer"
                    :src="formattedAudioUrl"
                    controls
                    style="width: 300px;"
                >
                  您的浏览器不支持音频播放
                </audio>
              </div>
              <div class="audio-placeholder" v-else style="color: #909399; padding: 0 20px;">
                请选择录音文件播放
              </div>
            </el-header>
            <el-main>
              <el-card shadow="hover" style="height: 100%;">
                <el-table :data="recordingList" size="mini" border>
                  <el-table-column
                      v-for="(col, inx) in tableRows15"
                      :key="inx"
                      :type="col.type"
                      :prop="col.prop"
                      :label="col.name"
                      :render-header="labelHead"
                      :show-overflow-tooltip="false"
                      align="center"
                      :min-width="getColumnWidth(col.label,col.prop,recordingList)"
                      header-align="center"
                      class-name="compact-cell">
                    <template slot-scope="scope">
                      <!-- 仅对目标字段添加点击事件 -->
                      <span v-if="['patientTell', 'nowHistory', 'beforeHistory'].includes(col.prop)"
                            @click="handleFieldClick(scope.row[col.prop], col.prop)"
                            style="color:#409EFF;cursor:pointer;">
                                      {{ scope.row[col.prop] }}
                              </span>
                      <span v-else>
                                 {{ scope.row[col.prop] }}
                              </span>
                    </template>
                  </el-table-column>
                  <el-table-column
                      label="操作"
                      fixed="right"
                      min-width="80"
                      align="center"
                      header-align="center">
                    <template slot-scope="scope">
                      <el-button
                          type="primary"
                          size="mini"
                          @click="handleAllFieldClick(scope.row)"
                      >
                        引用
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-main>
          </el-container>
        </el-container>
      </el-dialog>
      <!-- 处置项目 -->
      <el-dialog
          :title="isShowPrescription ? '查看处置项目' : '选择处置项目'"
          :close-on-click-modal="false"
          :visible.sync="selDoctordisposeDialog"
          width="70%"
      >
        <el-form :inline="true" :model="searchForm" class="search-form" style="margin-top: -20px">
          <!-- 7个输入框 -->
          <el-form-item label="健康ID:">
            <el-input v-model="patientForm.patId" :disabled="true" style="width: 200px" size="mini"></el-input>
          </el-form-item>
          <el-form-item label="姓名:">
            <el-input v-model="patientForm.name" type="textarea" :autosize="{ minRows: 1, maxRows: 1 }" :disabled="true"
                      size="mini"></el-input>
          </el-form-item>
          <el-form-item label="诊断:">
            <el-input v-model="addSeedoctorForm.westernDiagnos" :disabled="true" style="width: 400px"
                      size="mini"></el-input>
          </el-form-item>

          <!-- 1个下拉框 -->
          <el-form-item label="处置项目:">
            <el-select v-model="searchForm.chargingPriceId" placeholder="请选择项目" :disabled="isShowPrescription"
                       @change="getChargingPriceDetail" size="mini" filterable clearable
                       style="width: 400px">
              <el-option
                  v-for="item in chargingPriceOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="单价:">
            <el-input v-model="searchForm.odcost" style="width: 50px" size="mini" :disabled="true"></el-input>
          </el-form-item>

          <el-form-item label="执行科室:">
            <el-select
                size="mini"
                :disabled="searchForm.depexecutetype === 0 || isShowPrescription"
                v-model="searchForm.deptName"
                placeholder="请选择科室"
                style="width: 100%">
              <el-option
                  v-for="item in deptOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <!--        <el-form-item label="数量:">
                    <el-input v-model="searchForm.count" style="width: 50px" size="mini"
                              :disabled="isShowPrescription"></el-input>
                  </el-form-item>-->
          <el-form-item label="备注:">
            <el-input v-model="searchForm.remark" style="width: 700px" size="mini"
                      :disabled="isShowPrescription"></el-input>
          </el-form-item>
          <el-button
              :disabled="doctordisposeTableData.some(item => item.id === this.searchForm.chargingPriceId) || isShowPrescription"
              style="margin-top: 7px;margin-left: 30px"
              type="primary"
              size="mini"
              @click="handleDisposeData()"
          >
            放入
          </el-button>
        </el-form>

        <el-table
            size="mini"
            :data="doctordisposeTableData"
            style="width: 100%"
            highlight-current-row
            @row-click="currentSelectedRow = $event"
        >
          <el-table-column label="操作" width="80" align="center">
            <template slot-scope="scope">
              <el-button
                  :disabled="isShowPrescription"
                  size="mini"
                  type="text"
                  @click="removeDoctordisposeSelected(scope.$index)"
              >移除
              </el-button>
            </template>
          </el-table-column>
          <el-table-column v-for="(col, inx) in tableRows9" :key="inx" :type="col.type" :prop="col.prop"
                           :label="col.name" :render-header="labelHead" align="center"
                           :min-width="getColumnWidth(col.label,col.prop,doctordisposeTableData)">
            <template #default="{ row }">
              {{ safeGetMappedValue(col, row, 'disposition') }}
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer no-line">
          <!--        <el-button
                      @click="currentSelectedRow && (doctordisposeTableData = doctordisposeTableData.filter(item => item.id !== currentSelectedRow.id))"
                      size="small" type="warning">移除
                  </el-button>-->

          <el-button type="primary" size="mini" @click="handleConfirmDisposeItem"
                     v-if="!isShowPrescription && permissionsArr.includes('system:docdispose:add')">确认选择
          </el-button>
          <el-button @click="handleCloseDoctordisposeTabel" size="mini">取消
          </el-button>
        </div>
      </el-dialog>

      <!-- 新增合约单位 -->
      <el-dialog :title="addUnitForm.id  == null ?'新增合约单位':'修改合约单位'" :before-close="handleCancelAddUnit"
                 :visible.sync="addUnitModalVisible" class="addUnitDialog" width="50%" :close-on-click-modal="false"
                 :modal="false">
        <div class="aform">
          <!-- 表单 -->
          <el-form :model="addForm" label-width="90px" size="mini" :rules="addUnitRules" ref="addUnitRef">
            <el-row :gutter="20">
              <el-col :span="v.spanRows" type="flex" v-for="(v,i) in addUnitType" :key="i"
                      :style="{ marginLeft: v.modelValue === 'uscc' ? '18px' : '0' }">
                <!-- input -->
                <el-form-item v-if="v.type === 'input'" :required="['code', 'name'].includes(v.modelValue)"
                              :label="v.label" :style="v.modelValue === 'uscc' ? 'white-space: nowrap' : ''">
                  <el-input :suffix-icon='v.prefix' v-model="$data.addUnitForm[v.modelValue]"
                            @input="handleNameChangeCode(v,i)"
                            :style="{ marginLeft: v.modelValue === 'uscc' ? '30px' : '0' }">

                  </el-input>
                </el-form-item>
                <!-- select -->
                <el-form-item v-if="v.type === 'select'" :label="v.label">
                  <el-select v-model="$data.addUnitForm[v.modelValue]" filterable
                             :disabled="v.modelValue === 'untAtte'">
                    <el-option v-for="item in $data[v.op]" :key="item.id" :label="item.label" :value="item.id">
                      <span style=" color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 新增的按钮区域 - 并排显示（添加在前，取消在后） -->
            <el-form-item style="margin-top: 20px; text-align: right">
              <el-button type="primary" size="mini" @click="handleAddContractUnit">
                {{ addUnitForm.id == null ? '新增' : '修改' }}
              </el-button>
              <el-button size="mini" @click="handleCancelAddUnit" style="margin-left: 10px">取消</el-button>
            </el-form-item>
          </el-form>
        </div>

      </el-dialog>

      <!-- 新增过敏原 -->
      <el-dialog
          :close-on-click-modal="false"
          :title="aiseAddRrEditTtiel"
          :before-close="handleCancelAiseForm"
          :visible.sync="aiseAddOrEditMedicineDialog"
          class="aiseAddOrEditMedicineDialog"
          width="600px">

        <div class="dialog-form-container">
          <el-form
              :model="aiseForm"
              :rules="aiseRules"
              label-width="100px"
              size="mini"
              ref="aiseFormRef"
              label-position="right">

            <!-- 第一行:名称 + 科室 -->
            <el-row :gutter="4">
              <el-col :span="12">
                <el-form-item label="名称:" prop="name">
                  <el-input
                      v-model="aiseForm.name"
                      @input="handleNameChangeCode(1,2)"
                      placeholder="请输入名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="编码:" prop="code">
                  <el-input
                      v-model="aiseForm.code"
                      placeholder="请输入编码"/>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="状态:" prop="state">
                  <el-select
                      v-model="aiseForm.state"
                      placeholder="请选择状态"
                      style="width: 100%">
                    <el-option
                        v-for="item in templateStateOption"
                        :key="item.id"
                        :label="item.label"
                        :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第二行:拼音简码 + 适用范围 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="拼音简码:" prop="pyCode">
                  <el-input
                      :disabled="true"
                      v-model="aiseForm.pyCode"
                      placeholder="自动生成"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="类型:" prop="type">
                  <el-select
                      v-model="aiseForm.type"
                      placeholder="请选择适用范围"
                      style="width: 100%">
                    <el-option
                        v-for="item in aiseTypeOption"
                        :key="item.id"
                        :label="item.label"
                        :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="备注:" prop="remark">
                  <el-input
                      v-model="aiseForm.remark"/>
                </el-form-item>
              </el-col>
            </el-row>


            <!-- 新增的按钮区域 - 并排显示（添加在前，取消在后） -->
            <el-form-item style="margin-top: 20px; text-align: right">
              <el-button type="primary" size="mini" @click="handleAiseAddOrEdit">
                确定
              </el-button>
              <el-button size="mini" @click="handleCancelAiseForm" style="margin-left: 10px">取消</el-button>
            </el-form-item>
          </el-form>
        </div>

      </el-dialog>

      <!-- 新增模板 -->
      <el-dialog
          :close-on-click-modal="false"
          :title="templateAddRrEditTtiel"
          :before-close="handleCancelTemplateForm"
          :visible.sync="tpAddOrEditMedicineDialog"
          class="tpAddOrEditMedicineDialog"
          width="600px">

        <div class="dialog-form-container">
          <el-form
              :model="templateForm"
              :rules="templateRules"
              label-width="100px"
              size="mini"
              ref="templateFormRef"
              label-position="right">

            <!-- 第一行:名称 + 科室 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="名称:" prop="name">
                  <el-input
                      v-model="templateForm.name"
                      @input="handleNameChangeCode(1)"
                      placeholder="请输入名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="科室:" prop="deptId">
                  <el-select
                      v-model="templateForm.deptId"
                      placeholder="请选择科室"
                      style="width: 100%">
                    <el-option
                        v-for="item in deptOptions"
                        :key="item.id"
                        :label="item.label"
                        :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第二行:拼音简码 + 适用范围 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="拼音简码:" prop="pinyin">
                  <el-input
                      :disabled="true"
                      v-model="templateForm.pinyin"
                      placeholder="自动生成"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="适用范围:" prop="rangeType">
                  <el-select
                      v-model="templateForm.rangeType"
                      placeholder="请选择适用范围"
                      style="width: 100%">
                    <el-option
                        v-for="item in rangeTypeOption"
                        :key="item.id"
                        :label="item.label"
                        :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第三行:状态 -->
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="状态:" prop="state">
                  <el-select
                      v-model="templateForm.state"
                      placeholder="请选择状态"
                      style="width: 100%">
                    <el-option
                        v-for="item in templateStateOption"
                        :key="item.id"
                        :label="item.label"
                        :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 主诉内容（文本域） -->
            <el-form-item label="内容:" prop="content">
              <el-input
                  type="textarea"
                  v-model="templateForm.content"
                  :rows="3"
                  placeholder="请输入主诉内容"
                  style="width: 100%"/>
            </el-form-item>

            <!-- 备注（文本域） -->
            <el-form-item label="备注:" prop="remark">
              <el-input
                  type="textarea"
                  v-model="templateForm.remark"
                  :rows="3"
                  placeholder="请输入备注"
                  style="width: 100%"/>
            </el-form-item>


            <!-- 新增的按钮区域 - 并排显示（添加在前，取消在后） -->
            <el-form-item style="margin-top: 20px; text-align: right">
              <el-button type="primary" size="mini" @click="handleAddTemplate">
                确定
              </el-button>
              <el-button size="mini" @click="handleCancelTemplateForm" style="margin-left: 10px">取消</el-button>
            </el-form-item>
          </el-form>
        </div>

      </el-dialog>

      <!-- 快速接诊 -->
      <el-dialog
          width="70vw"
          height="70vh"
          title="快速接诊"
          :close-on-click-modal="false"
          :before-close="handleCancelContract"
          :visible.sync="receptionModalVisible"
          class="receptionDialog"
      >
        <div class="aform">
          <el-form
              ref="patientFormRef"
              :model="patientForm"
              label-width="90px"
              size="mini"
              class="compact-form"
              :rules="patientFormRules"
          >
            <!-- 第一行 - 基本信息 -->
            <el-row :gutter="15" class="form-row">
              <el-col :span="6">
                <el-form-item label="健康ID:">
                  <el-input
                      v-model="patientForm.patId"
                      size="mini"
                      placeholder="输入关键字后按回车键搜索"
                      @keyup.enter.native="handleSearch"
                      :disabled="isInputDisabled"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="姓名:" prop="name">
                  <el-input
                      v-model="patientForm.name"
                      :disabled="isInputDisabled"
                      size="mini"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="性别:" prop="sex">
                  <el-select
                      v-model="patientForm.sex"
                      size="mini"
                      style="width: 100%"
                  >
                    <el-option label="男" value="1"/>
                    <el-option label="女" value="2"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="出生日期:">
                  <el-date-picker
                      v-model="patientForm.brdy"
                      type="date"
                      size="mini"
                      style="width: 100%"
                      placeholder="身份证自动计算"
                      :disabled="true"
                      prefix-icon="none"
                      value-format="yyyy-MM-dd"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第二行 - 证件信息 -->
            <!-- 第二行 - 证件信息 -->
            <el-row :gutter="22" class="form-row">
              <el-col :span="6">
                <el-form-item>
                  <div style="display: flex">
                    <el-select
                        v-model="patientForm.identityCard"
                        size="mini"
                        style="width: 115px; margin-right: 0"
                        filterable
                        clearable
                    >
                      <el-option v-for="item in certypeOption" :key="item.id" :label="item.label" :value="item.id"/>
                    </el-select>
                    <el-input
                        v-model="patientForm.certno"
                        style="width: 200px"
                        @blur="certnoMonitor"
                        @clear="patientForm.ageYear = null;patientForm.ageMonth = null;patientForm.brdy = '';"
                        clearable
                        maxlength="18"
                        show-word-limit
                    />
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item style="margin-left: 100px;">
                  <div class="age-input-group">
                    <el-input
                        v-model="patientForm.ageYear"
                        :disabled="true"
                        size="mini"
                        style="width: 40px;"
                    />
                    <span class="age-unit">岁</span>
                    <el-input
                        v-model="patientForm.ageMonth"
                        :disabled="true"
                        size="mini"
                        style="width: 40px;"
                    />
                    <span class="age-unit">月</span>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="病员类型:">
                  <el-select
                      v-model="patientForm.prhType"
                      size="mini"
                      style="width: 130px"
                  >
                    <el-option
                        v-for="item in prhTypeOption"
                        :key="item.id"
                        :label="item.label"
                        :value="item.id"
                    >
                      <span style="color: #8492a6; font-size: 12px">{{ item.label }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="2">
                <el-form-item label="三无:">
                  <el-checkbox
                      v-model="patientForm.thrNot"
                      :true-label="1"
                      :false-label="0"
                      @change="handleThrNotChange"
                      size="mini">
                  </el-checkbox>
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label="孕妇:" prop="pregnant">
                  <el-checkbox
                      v-model="patientForm.pregnant"
                      :true-label="1"
                      :false-label="0"
                      :disabled="patientForm.sex === '1' || patientForm.sex === null"
                  >
                  </el-checkbox>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第三行 - 个人信息 -->
            <el-row :gutter="4" class="form-row">
              <el-col :span="6">
                <el-form-item label="民族:">
                  <el-select
                      v-model="patientForm.naty"
                      size="mini"
                      style="width: 100%"
                      filterable
                      clearable
                  >
                    <el-option v-for="item in nationOption" :key="item.id" :label="item.label" :value="item.id"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="国籍:">
                  <el-select
                      v-model="patientForm.ntlyId"
                      size="mini"
                      style="width: 100%"
                      filterable
                      clearable
                  >
                    <el-option v-for="item in ntlyOptions" :key="item.id" :label="item.label" :value="item.id"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="职业:">
                  <el-select
                      v-model="patientForm.jobId"
                      size="mini"
                      style="width: 100%"
                      filterable
                      clearable
                  >
                    <el-option v-for="item in jobOption" :key="item.id" :label="item.label" :value="item.id"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第四行 - 联系方式 -->
            <el-row :gutter="24" class="form-row">
              <el-col :span="8">
                <el-form-item label="本人电话:" prop="tel">
                  <el-input
                      @blur="validateTel('tel')"
                      v-model="patientForm.tel"
                      size="mini"
                      style="width: 100%"
                      placeholder="请输入11位手机号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系人:">
                  <el-input
                      type="textarea" :autosize="{ minRows: 1, maxRows: 1 }"
                      v-model="patientForm.conerName"
                      size="mini"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系电话:" prop="conerTel">
                  <el-input
                      @blur="validateTel('conerTel')"
                      v-model="patientForm.conerTel"
                      size="mini"
                      style="width: 100%"
                      placeholder="请输入11位手机号"
                  />
                </el-form-item>
              </el-col>

            </el-row>

            <!-- 第五行 - 籍贯地址 -->
            <el-row :gutter="15" class="form-row">
              <el-col :span="24">
                <el-form-item label="籍贯地址:" prop="naplAddName" class="address-form-item">
                  <div style="display: flex;">
                    <el-cascader
                        :key="addressKey"
                        ref="naplAddCodeArrRef"
                        v-model="patientForm.naplAddCodeArr"
                        :props="addressProps"
                        :options="provinces"
                        @focus="initAddressData('napl')"
                        :placeholder="naplPleasett"
                        style="width: 400px;"
                    />
                    <el-input
                        v-model="patientForm.naplAddName"
                        clearable
                        placeholder="门牌号"
                        style="width: 100%; margin-left: -1px;"
                    />
                  </div>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第六行 - 联系地址 -->
            <el-row :gutter="15" class="form-row">
              <el-col :span="24">
                <el-form-item label="联系地址:" prop="conerAddName">
                  <div style="display: flex;">
                    <el-cascader
                        size="mini"
                        ref="conerAddCodeArrRef"
                        :key="addressKey"
                        v-model="patientForm.conerAddCodeArr"
                        :props="addressProps"
                        :options="provinces"
                        @focus="initAddressData"
                        :placeholder="conerPleasett"
                        style="width: 400px;"
                        :input-style="{ '::placeholder': { color: '#000' } }"
                    />
                    <el-input
                        size="mini"
                        v-model="patientForm.conerAddName"
                        clearable
                        placeholder="门牌号"
                        style="width: 100%; margin-left: -1px;"
                    />
                  </div>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第七行 - 挂号信息 -->
            <el-row :gutter="15" class="form-row">
              <el-col :span="8">
                <el-form-item label="挂号类别:">
                  <el-select
                      v-model="receptionForm.regTypeId"
                      size="mini"
                      style="width: 100%"
                      @change="handleRegTypePrice"
                  >
                    <el-option v-for="item in registerOptions" :key="item.id" :label="item.label" :value="item.id"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="挂号金额:">
                  <el-input
                      v-model="receptionForm.price"
                      size="mini"
                      style="width: 100%"
                      :disabled="true"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="病员费别:">
                  <el-select
                      v-model="fastReceptionForm.prhCostType"
                      size="mini"
                      style="width: 100%"
                      filterable
                      clearable
                  >
                    <el-option v-for="item in prhCostOption" :key="item.id" :label="item.label" :value="item.id"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <!-- 操作按钮 -->
          <div class="dialog-footer no-line">
            <el-button size="mini" type="primary" @click="handleIdCardData">
              身份证读取
            </el-button>
            <el-button size="mini" type="warning" @click="handleResetContract">
              重置
            </el-button>
            <el-button size="mini" type="primary" @click="handleAddFastReception" :loading="loading">
              确定
            </el-button>
            <el-button size="mini" type="danger" @click="handleCancelContract">
              取消
            </el-button>
          </div>
        </div>
      </el-dialog>

      <el-dialog
          title="患者选择"
          :visible.sync="patientDialogVisible"
          width="60%"
          :before-close="handleCloseChoosePatient"
          class="patient-dialog"
      >
        <!-- 患者表格 - 固定高度，超出部分滚动 -->
        <el-table
            size="mini"
            :data="patientTabelData"
            border
            highlight-current-row
            @row-dblclick="handleChoosePatient"
            @current-change="handleClickRow"
            style="width: 100%;"
            height="400px"
        >
          <el-table-column v-for="(col, inx) in tableRows14" :key="inx" :type="col.type" :prop="col.prop"
                           :label="col.name" :render-header="labelHead" align="center"
                           :min-width="getColumnWidth(col.label,col.prop,patientTabelData)">
            <template #default="{ row }">
              {{ safeGetMappedValue(col, row) }}
            </template>
          </el-table-column>
        </el-table>

        <div class="dialog-footer no-line">
          <el-button type="primary" @click="handleChoosePatient" size="mini" :loading="loading">确定</el-button>
          <el-button @click="handleCloseChoosePatient" size="mini">取消</el-button>
        </div>
      </el-dialog>

      <!--一周内就诊数据-->
      <el-dialog
          :close-on-click-modal="false"
          title="一周内就诊数据"
          :visible.sync="sevenDayDialogVisible"
          :before-close="handleCancelSeedoctorDataList"
          width="70%"
          class="patient-dialog"
      >
        <!-- 查询条件区域 -->
        <div class="query-conditions">
          <el-form :inline="true" :model="seedoctorQueryParams" class="query-form" size="mini">
            <el-form-item label="健康ID:">
              <el-input
                  style="width: 150px"
                  v-model="seedoctorQueryParams.patientId"
                  clearable
              ></el-input>
            </el-form-item>

            <el-form-item label="姓名:">
              <el-input
                  style="width: 150px"
                  v-model="seedoctorQueryParams.patientName"
                  clearables
              ></el-input>
            </el-form-item>

            <el-form-item label="就诊时间:">
              <el-date-picker
                  style="width: 150px"
                  v-model="seedoctorQueryParams.startTime"
                  type="date"
                  placeholder="开始日期"
                  value-format="yyyy-MM-dd"
                  @change="handleSavenData"
              ></el-date-picker>
              -
              <el-date-picker
                  style="width: 150px"
                  v-model="seedoctorQueryParams.endTime"
                  type="date"
                  placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  @change="handleSavenData"
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="就诊医生:">
              <el-select
                  style="width: 100px"
                  v-model="seedoctorQueryParams.doctorId"
                  clearable
                  @change="handleSavenData"
              >
                <el-option
                    v-for="item in doctorOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSavenData" size="mini">查询</el-button>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" size="mini" @click="batchDeriveExcelSeeDoctorData">导出Excel</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 表格区域 -->
        <div class="table-container">
          <el-table
              size="mini"
              :key="queryKey"
              :data="sevenDayTableData"
              @row-dblclick="getHistoryMedicalData"
              ref="printTable"
              border
              style="width: 100%"
          >
            <el-table-column
                label="操作"
                width="160"
                align="center"
                fixed="right"
            >
              <template #default="{ row }">
                <el-button
                    type="success"
                    size="mini"
                    @click="handleAddReception(row)"
                    title="接诊"
                >接诊
                </el-button>
                <el-button
                    type="success"
                    size="mini"
                    @click="handleQuote(row)"
                    title="反诊"
                >反诊
                </el-button>
              </template>
            </el-table-column>

            <el-table-column
                v-for="(col, index) in tableRows3"
                :key="index"
                :prop="col.prop"
                :label="col.name"
                align="center"
                :min-width="getColumnWidth(col.label, col.prop, sevenDayTableData)"
            >
              <template #default="{ row }">
                {{ safeGetMappedValue(col, row) }}
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalSize"
              class="pagination"
          ></el-pagination>
        </div>

        <div slot="footer">
          <el-button @click="handleCancelSeedoctorDataList" size="mini">取消</el-button>
        </div>
      </el-dialog>

      <!--一周内就诊数据医嘱-->
      <el-dialog
          :close-on-click-modal="false"
          title="历史医嘱"
          :visible.sync="historyMedicalDialogVisible"
          width="70%"
          class="patient-dialog"
      >
        <div class="table-container">
          <el-table
              size="mini"
              :data="historyMedicalData"
              border
              style="width: 100%"
              show-summary
              :summary-method="getPricSummary"
          >
            <el-table-column
                v-for="(col, index) in tableRows10"
                :key="index"
                :prop="col.prop"
                :label="col.name"
                align="center"

                :min-width="getColumnWidth(col.label, col.prop, historyMedicalData)"
            >
              <template #default="{ row }">
                {{ safeGetMappedValue(col, row) }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div slot="footer">
          <el-button @click="historyMedicalDialogVisible = false" size="mini">取消</el-button>
        </div>
      </el-dialog>

      <!--西医诊断-->
      <el-dialog
          :close-on-click-modal="false"
          title="西医诊断"
          :visible.sync="westernDiagnosisModalVisible"
          :before-close="handleCancelSelDiagnose"
          width="60%"
          class="patient-dialog"
      >
        <!-- 搜索框区域 -->
        <div class="search-container" style="display: flex; align-items: center; margin-bottom: 15px;">
          <span style="margin-right: 12px; font-size: 14px; color: #606266; font-weight: 500;">搜索</span>
          <el-input
              size="small"
              placeholder="请输入诊断名称搜索"
              v-model="westernSearchQuery"
              clearable
              style="width: 320px; "
              @clear="resetDiagnoseData(1)"
              @keyup.enter.native="handleWesternSearch"
          >
            <el-button
                slot="append"
                icon="el-icon-search"
                @click="handleWesternSearch"
                style="padding: 9px 12px;"
            ></el-button>
          </el-input>
        </div>

        <!-- 第一个表格（固定高度） -->
        <div style="height:300px; margin-bottom: 15px;">
          <el-table
              ref="westernTable"
              sizi="mini"
              :data="westernDiagnosisTableData"
              border
              highlight-current-row
              style="width: 100%;"
              height="100%"
              class="compact-mini-table"
              @row-dblclick="addToWesternSelectedTable"
          >
            <el-table-column
                v-for="(col, inx) in tableRows4"
                :key="inx"
                :type="col.type"
                :prop="col.prop"
                :label="col.name"
                :render-header="labelHead"
                align="center"
                :min-width="getColumnWidth(col.label,col.prop,westernDiagnosisTableData)"
                :width="col.prop === 'remarks' ? '700px' : null"
            ></el-table-column>
          </el-table>
        </div>

        <!-- 已选列表（使用el-tabs包装） -->
        <el-tabs type="border-card" style="box-shadow: none; border: 1px solid #ebeef5;">
          <el-tab-pane label="已选诊断列表">
            <el-table
                size="mini"
                :data="westernSelectedTable"
                border
                style="width: 100%"
                empty-text="请双击上方表格添加诊断"
                class="compact-mini-table"
            >
              <el-table-column label="操作" width="80" align="center">
                <template slot-scope="scope">
                  <el-button
                      size="mini"
                      type="text"
                      @click="removeWesternSelected(scope.$index)"
                  >移除
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column
                  v-for="(col, inx) in tableRows8"
                  :key="inx"
                  :prop="col.prop"
                  :label="col.name"
                  :render-header="labelHead"
                  align="center"
                  :min-width="getColumnWidth(col.label,col.prop,westernSelectedTable)"
              >
                <template slot-scope="scope">
                  <template v-if="col.prop === 'definiteDiagnosis'">
                    <el-checkbox
                        v-model="scope.row.definiteDiagnosis"
                        :true-label="1"
                        :false-label="0"
                        @change="(val) => handleConfirmed(scope.row, val)"
                    ></el-checkbox>
                  </template>
                  <template v-else>
                    {{ safeGetMappedValue(col, scope.row) }}
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>

        <div slot="footer" class="dialog-footer no-line">
          <el-button type="primary" @click="addReceptionDiagnosis(1)" size="mini" :loading="loading">确定</el-button>
          <el-button @click="handleCancelSelDiagnose" size="small">取消</el-button>
        </div>
      </el-dialog>

      <!--中医诊断-->
      <el-dialog
          :close-on-click-modal="false"
          title="中医诊断"
          :visible.sync="chinaDiagnosisModalVisible"
          :before-close="handleCancelSelDiagnose"
          width="60%"
          class="patient-dialog"
      >
        <!-- 双表格并排展示 -->
        <el-row :gutter="20">
          <el-col :span="14">
            <!-- 第一个表格的病症列表搜索框 -->
            <div class="search-container" style="margin-bottom: 15px; align-items: center;">
              <span style="margin-right: 10px; font-size: 14px;">搜索:</span>
              <el-input
                  size="mini"
                  placeholder="请输入诊断名称搜索"
                  v-model="chinaSearchQuery1"
                  clearable
                  style="width: 300px"
                  @clear="resetDiagnoseData(2)"
                  @keyup.enter.native="handleChinaSearch(1)"
              >
                <el-button slot="append" @click="handleChinaSearch(1)">查询</el-button>
              </el-input>
            </div>

            <!-- 第一个表格（固定高度） -->
            <div style="height: 300px;">
              <el-table
                  size="mini"
                  :data="chinaDiagnosisTableData1"
                  border
                  highlight-current-row
                  style="width: 100%;"
                  height="100%"
                  @row-click="selChinaDiagnosisRow"
              >
                <el-table-column
                    v-for="(col, inx) in tableRows4"
                    :key="inx"
                    :type="col.type"
                    :prop="col.prop"
                    :label="col.name"
                    :render-header="labelHead"
                    align="center"
                    :min-width="getColumnWidth(col.label,col.prop,chinaDiagnosisTableData1)"
                ></el-table-column>
              </el-table>
            </div>
          </el-col>

          <el-col :span="10">
            <!-- 第二个表格的筛选搜索框 -->
            <div class="search-container" style="margin-bottom: 15px; align-items: center;">
              <span style="margin-right: 10px; font-size: 14px;">搜索:</span>
              <el-input
                  size="mini"
                  placeholder="请输入筛选条件"
                  v-model="chinaSearchQuery2"
                  clearable
                  style="width: 300px"
                  @clear="resetDiagnoseData(3)"
                  @keyup.enter.native="handleChinaSearch(2)"
              >
                <el-button slot="append" @click="handleChinaSearch(2)">查询</el-button>
              </el-input>
            </div>

            <!-- 第二个表格（固定高度） -->
            <div style="height: 300px;">
              <el-table
                  size="mini"
                  :data="chinaDiagnosisTableData2"
                  border
                  highlight-current-row
                  style="width: 100%;"
                  height="100%"
                  @row-dblclick="addToChinaSelectedTable"
              >
                <el-table-column
                    v-for="(col, inx) in tableRows5"
                    :key="inx"
                    :type="col.type"
                    :prop="col.prop"
                    :label="col.name"
                    :render-header="labelHead"
                    align="center"
                    :min-width="getColumnWidth(col.label,col.prop,chinaDiagnosisTableData2)"
                ></el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>

        <!-- 已选列表（使用el-tabs包装） -->
        <el-tabs type="border-card" style="box-shadow: none; border: 1px solid #ebeef5; margin-top: 15px;">
          <el-tab-pane label="已选诊断列表">
            <el-table
                size="mini"
                :data="chinaSelectedTable"
                border
                style="width: 100%;"
                empty-text="请双击上方表格添加诊断"
            >
              <el-table-column label="操作" width="80" align="center">
                <template slot-scope="scope">
                  <el-button
                      size="mini"
                      type="text"
                      @click="removeChinaSelected(scope.$index)"
                  >移除
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column
                  v-for="(col, inx) in tableRows6"
                  :key="inx"
                  :prop="col.prop"
                  :label="col.name"
                  :render-header="labelHead"
                  align="center"
                  :min-width="getColumnWidth(col.label,col.prop,chinaSelectedTable)"
              ></el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>

        <div slot="footer" class="dialog-footer no-line">
          <el-button type="primary" @click="addReceptionDiagnosis(2)" size="mini" :loading="loading">确定</el-button>
          <el-button @click="handleCancelSelDiagnose" size="small">取消</el-button>
        </div>
      </el-dialog>

      <!--制法脚注-->
      <el-dialog
          :close-on-click-modal="false"
          title="制法选择"
          :visible.sync="creationMethodDialogVisible"
          width="600px">

        <!-- 紧凑的4列布局 -->
        <div class="compact-method-grid">
          <div
              v-for="(col, index) in chinaMakeOptions"
              :key="index"
              :class="{highlight:active===index}" @click="handleCheckedChinaMakeMethod(col,index)"
              class="compact-method-item">
            {{ col.label }}
          </div>
        </div>

        <div slot="footer" class="dialog-footer no-line">
          <el-button @click="handleAddChinaMakeMethod" type="success" size="mini">确定</el-button>
          <el-button @click="creationMethodDialogVisible = false" type="warning" size="mini">取消</el-button>
        </div>
      </el-dialog>

      <!--修改用量-->
      <el-dialog
          :close-on-click-modal="false"
          title="修改用量"
          :visible.sync="showDoseDialog"
          width="20%"
          :before-close="handleClose">
        <el-form size="mini" label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item
                  label="中药用量:"
                  prop="executionDays"
              >
                <el-input
                    style="width: 60%"
                    :min="1"
                    step="1"
                    v-model.number="editDoseValue"
                    type="number"
                    @change="validateDose"
                    placeholder="请输入用量">
                  <template slot="append">g</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer no-line">
    <el-button type="primary" @click="confirmEditDose">确 定</el-button>
    <el-button @click="showDoseDialog = false">取 消</el-button>
  </span>
      </el-dialog>

      <!--是否皮试-->
      <el-dialog
          :close-on-click-modal="false"
          title="确认是否皮试"
          :visible.sync="isSkinTestDoseDialog"
          width="400px"
          :before-close="handleCancelSkinTest">

        <el-form size="mini" ref="skinTestForm" :model="westernMedicineSearchQuery" label-width="60px"
                 :rules="westernMedicineRules">
          <el-row>
            <el-col :span="24">
              <el-form-item label="名称:" prop="drugName">
                <el-input
                    disabled
                    v-model="westernMedicineSearchQuery.drugName"
                    style="width: 100%">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="皮试:" prop="isSkinTest">
                <el-select
                    v-model="westernMedicineSearchQuery.isSkinTest"
                    style="width: 100%">
                  <el-option
                      v-for="item in skintstDicmOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <span slot="footer" class="dialog-footer no-line">
    <el-button type="primary" @click="handleConfirmSkinTest" size="mini">确定</el-button>
    <el-button @click="handleCancelSkinTest" size="mini">取消</el-button>
  </span>
      </el-dialog>


      <!--选择频次-->
      <el-dialog
          :close-on-click-modal="false"
          title="选择执行频率"
          :visible.sync="selExecutionPLDialogVisible"
          width="20%"
          :before-close="handleExecutionPL">

        <el-form size="mini" label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item :model="searchForm" label="执行频率:">
                <el-select
                    size="mini"
                    :disabled="searchForm.depexecutetype === 0 || isShowPrescription"
                    v-model="searchForm.deptName"
                    placeholder="请选择科室"
                    style="width: 70%">
                  <el-option
                      v-for="item in deptOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item :model="searchForm" label="执行频率:">
                <el-select
                    filterable
                    @change="computeFrequency"
                    v-model="searchForm.usedfrquId"
                    style="width: 70%"
                    placeholder="请选择执行频率">
                  <el-option
                      v-for="item in medicationFrequencyOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"/>
                </el-select>
              </el-form-item>

              <el-form-item
                  label="执行天数:"
                  prop="executionDays"
              >
                <el-input
                    @input="computeFrequencyDay"
                    type="number"
                    min="1"
                    step="1"
                    style="width: 70%"
                    v-model.number="searchForm.executionDays"
                    placeholder="请输入执行天数"
                ></el-input>
              </el-form-item>

              <el-form-item
                  label="执行数量:"
                  prop="executionDays"
              >
                <el-input
                    @change="computeFrequencyNum"
                    type="number"
                    min="1"
                    step="1"
                    style="width: 70%"
                    v-model.number="searchForm.executionNum"
                    placeholder="请输入数量"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <span slot="footer" class="dialog-footer no-line">
    <el-button type="primary" @click="handleDisposeData(true)" size="mini">确定</el-button>
    <el-button @click="handleExecutionPL" size="mini">取消</el-button>
  </span>
      </el-dialog>
      <drugInfoDialog  ref="drugDialog" v-if="showDrugDialog" :visible.sync="showDrugDialog"></drugInfoDialog>
      <basicInfo ref="basicInfo" :form="westSonData" v-if="showDrugDialog" class="hidden-dialog"></basicInfo>
<!--      <kzInfo ref="kzInfo" :form="westSonData" v-if="showDrugDialog"></kzInfo>
      <useInfo ref="useInfo" :form="westSonData" v-if="showDrugDialog"></useInfo>-->
    </div>
  </div>

</template>

<script>
import {
  addContractUnit,
  addDocphr,
  dict,
  editContractUnit,
  editDocphr,
  getArea,
  getContractUnit,
  getContuntList,
  getDeptList,
  getRegisterType
} from "@/api/reservation/reservation";
import AddType from './reservationAddType.js'
import AddType2 from './reservationSettleType.js'
import drugInfoDialog from "@/views/systemCatalogue/xicheng/Western/addDialogVisible.vue";
import basicInfo from '/src/views/systemCatalogue/xicheng/Western/F2.vue';
import westAddForm from '/src/views/systemCatalogue/xicheng/Western/addForm.js'
// 从第3个JS文件中导入字段配置 扩展信息
import kzInfo from '/src/views/systemCatalogue/xicheng/Western/F3.vue';
// 从第4个JS文件中导入字段配置 使用注意
import useInfo from '/src/views/systemCatalogue/xicheng/Western/F4.vue';
import {pinyin} from "pinyin-pro";
import {
  addAise,
  addBeforeHistoryTemplate,
  addChinaPrescription,
  addComplainTemplate,
  addDoctordispose,
  addFastReception,
  addMedicalAudio, addMedicineCache,
  addNowHistoryTemplate,
  addReception,
  addWestPrescription,
  batchDeriveExcelSeeDoctorData,
  delOneAdvice,
  editAise,
  editBeforeHistoryTemplate,
  editComplainTemplate,
  editDoctoradvice,
  editNowHistoryTemplate,
  editReception,
  editReceptionDiagnosis,
  editWestPrescription,
  getAiseList,
  getBeforeHistoryTemplate,
  getChargingPriceById,
  getChinaDiseaseByCondition,
  getChinaDocticdList,
  getChinaDugdpurctable,
  getChinaPrescription,
  getComplainTemplate,
  getDeptInDoctorList,
  getDiagnosisInfo,
  getDocphrByCondtion,
  getDocphrList,
  getDocticdList,
  getDoctoradvice,
  getDoctordispose,
  getDoesItExistSFZ,
  getDrugUnt,
  getFinishReception,
  getMedicalAudioList, getMedicineCache,
  getNowHistoryTemplate,
  getOneSeeDoctorData, getPatientAllData,
  getReceptionCancel,
  getReceptionDiagnosis,
  getReceptionList,
  getSyndromeByCondition,
  getSyndromeList,
  getWestDugdpurctable,
  getWestPrescription,
  printOutpatientsDerive,
  uploadFile,
} from "@/api/reservation/outpatientPhysician";
import {getChargingPrice, getCosrute} from "@/api/cosrute/Cosrute";
import {getDoctorList} from "@/api/scheduling/scheduling";
import {getDInfos, getDosaUnt, getMedicationWay} from "@/api/MedicenCata";
import {selectDrugDosageForm} from "@/api/systemCatalogue/Pharmacological";
import dayjs from "dayjs";
import printUtil from "@/untils/printUtil";
import {medicalRecordOutpatient} from "@/assets/printTemplateConfig/medicalRecordOutpatient";
import {outpatientsDiagnosis} from "@/assets/printTemplateConfig/outpatientsDiagnosis";
import {outpatientsDiagnosis2} from "@/assets/printTemplateConfig/outpatientsDiagnosis2";
import {debounce} from "@/untils/debounce";
import {readIdCard} from "@/untils/idCardReader";
import {getNationalityId} from "@/untils/outpatientPhysicianUntils";
import {withLoading} from "@/untils/loading";
import {doccliniclist} from "@/api/cinic/cinic";
import {westPrescription} from "@/assets/printTemplateConfig/westPrescription";
import {chinaPrescription} from "@/assets/printTemplateConfig/chinaPrescription";
import {getStaff} from "@/api/user";
import {getSeeDoctorKeywordList} from "@/api/seedoctorKeyword/seedoctorKeyword";

export default {
  components: {
    drugInfoDialog,
    basicInfo,
    kzInfo,
    useInfo
  },
  data() {
    return {
      provinces:[],
      DropDownedName: '西药医嘱',

      activeGroup: null,
      activeField: null,
      keywordsVisible: false,
      keywordGroups: {
        // 主诉分组
        patientTell: [
          {type: 1, title: '呼吸系统', keywords: []},
          {type: 2, title: '消化系统', keywords: []},
          {type: 3, title: '心脏血管', keywords: []},
          {type: 4, title: '外科症状', keywords: []}
        ],
        // 现病史分组
        nowHistory: [
          {type: 1, title: '诱因', keywords: []},
          {type: 2, title: '特征', keywords: []},
          {type: 3, title: '兼症', keywords: []},
          {type: 4, title: '精神', keywords: []},
          {type: 5, title: '睡眠', keywords: []},
          {type: 6, title: '饮食', keywords: []},
          {type: 7, title: '二便', keywords: []},
          {type: 8, title: '体态', keywords: []}
        ],
        // 既往史分组
        beforeHistory: [
          {type: 1, title: '默认', keywords: []},
          {type: 2, title: '既往有', keywords: []},
          {type: 3, title: '个人史', keywords: []}
        ]
      },

      medicalRecord: false,
      outpatientsDiagnosis: false,
      medicalRecordHTML: '',
      outpatientsDiagnosisHTML: '',

      activeCollapse: ['seeDoctorData', 'medical'],

      westPagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      chinaPagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },


      // 防抖相关
      westSearchDebounce: null,
      chinaSearchDebounce: null,
      searchDebounceTime: 500,

      diseaseList: '高血压、动脉硬化性心脏病、冠状动脉粥样硬化性心脏病、脑卒中、糖尿病、慢性阻塞性肺疾病、慢性肾脏病、冠状动脉粥样硬化、冠状动脉狭窄',
      color: [
        '#FF0000', // 红
        '#00FF00', // 绿
        '#0000FF', // 蓝
        '#FF00FF', // 紫
        '#FFA500', // 橙
        '#00FFFF', // 青
        '#FF1493', // 深粉
        '#32CD32', // 酸橙
        '#8A2BE2', // 蓝紫
        '#FFD700', // 金
        '#006400', // 深绿
        '#8B008B', // 深紫
        '#FF6347', // 番茄红
        '#1E90FF', // 道奇蓝
        '#9370DB', // 中紫
        '#3CB371'  // 中海绿
      ],
      addressKey: null,
      isInitialLoad: true,
      certLengthMap: {
        1: 18,  // 居民身份证
        2: 20,  // 居民户口簿
        3: 9,   // 护照
        4: 10,  // 军官证
        5: 12,  // 驾驶证
        6: 11,  // 港澳居民来往内地通行证
        7: 10,  // 台湾居民来往内地通行证
        8: 18,  // 中国人民武装警察身份证件
        9: 20   // 其他法定有效证件
      },
      // 证件格式验证规则
      certPatterns: {
        1: /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/,
        2: /^[A-Za-z0-9\u4e00-\u9fa5]{1,20}$/,
        3: /^[A-Za-z]\d{7,8}$/,
        4: /^[A-Za-z0-9\u4e00-\u9fa5]{1,10}$/,
        5: /^\d{12}$/,
        6: /^[HMhm]\d{8,10}$/,
        7: /^\d{8}[A-Za-z]{2}$/,
        8: /^WJ\d{6}\d{11}$/,
        9: /^[A-Za-z0-9\u4e00-\u9fa5]{1,20}$/
      },

      userInfo: null,
      userPermission: {},
      searchForm: {
        deptName: '',
        odcost: null,
        executeOdcost: null,
        count: 1,
        remark: '',
        chargingPriceId: null,
        depexecutetype: null,
        usedfrquId: null,
        executionDays: null,
        executionNum: null,
      },
      
      visitStateOption: [{id: 1, label: '待签到'}, {id: 2, label: '待就诊'}, {id: 3, label: '已接诊'},
        {id: 4, label: '已取消'}, {id: 5, label: '待分诊'}, {id: 6, label: '已失效'}],
      
      currentPage: 1,      // 当前页码
      pageSize: 10,
      pageNum: 1, //当前页currentPage
      totalSize: 10, //总条数
      
      patientDialogVisible: false,
      patientTabelData: [],
      sevenDayTableData: [],
      historyMedicalData: [],
      queryKey: 0,

      
      chinaDiagnosisTableData1: [],
      chinaDiagnosisTableData2: [],
      chinaSelectedTable: [],
      selChinaDiagnosis: {},

      westernMedicineRules: {
        drugName: [
          {required: true, message: '药品名称不能为空', trigger: 'blur'}
        ],
        isSkinTest: [
          {required: true, message: '请选择是否皮试', trigger: 'change'}
        ]
      },
      
      westernMedicineSearchQuery: {
        id: '',
        drugName: '',
        isSkinTest: null,
      },
      
      chinaMedicineSearchQuery: '',
      westMedicineSearchQuery: '',
      chinaChekeCurrentData: {},
      searchTriggered: false,
      showWestTable: false,
      showChinaTable: false,
      showDrugDialog: false,
      showBasicInfo: false,
      showKzInfo: false,
      showUseInfo: false,

      westernSearchQuery: '',
      chinaSearchQuery1: '',
      chinaSearchQuery2: '',
      westernDiagnosisTableData: [],
      westernSelectedTable: [],

      addWesternForm: {
        id: null,
        age: null,
        ageVar: '',
        agnterAddr: '',
        agnterCertType: null,
        agnterCretno: '',
        agnterName: '',
        agnterRlts: null,
        agnterTel: '',
        bilgDeptId: null,
        bilgDrId: null,
        bilgOptId: null,
        dugDrxDetailsVOS: [],
        icdCode: '',
        icdName: '',
        mainRxId: null,
        name: '',
        opspRx: false,
        phayId: 1,
        pricingType: null,
        purcAmt: null,
        reAmt: null,
        regId: null,
        remark: '',
        rxFrom: null,
        rxType: 1,
        saleAmt: null,
        seeDoctorId: null,
        seeId: null,
        sex: null,
        skintstRx: null,
        state: null,
        patientId: null,
        frquCnt: null,
        isWestPrint: false,
      },
      addChinaForm: {
        age: null,
        ageVar: '',
        bilgDeptId: null,
        extgCnt: null,
        extgType: 0,
        icdCode: '',
        icdName: '',
        medcWayId: 7,
        name: '',
        opspRx: false,
        phayId: 2,
        pricingType: null,
        purcAmt: null,
        regId: null,
        remark: '',
        rxDosCnt: null,
        rxDosUnt: '',
        rxType: 1,
        saleAmt: null,
        seeId: null,
        sex: null,
        state: null,
        tcmCnt: 1,
        tcmDetailsVOS: [],
        tcmWayId: 1,
        tcmWayName: "",
        usedfrquId: 3,
        predictMoney: null,
        chinaMedicineSum: null,
        takeMedicineWay1: 3,
        takeMedicineWay2: 1,
        sdoseCnt: null,
        patientId: null,
        brdy: '',
        useMethod: '',
        isChinaPrint: false,
      },

      //血糖类型1空腹2随机3餐后
      bloodTypeOptions: [{id: '1', label: '空腹'}, {id: '2', label: '随机'}, {id: '3', label: '餐后'}],
      
      westAddForm: {},

      westernMedicineForm: {
        age: null,
        ageVar: '',
        agnterAddr: '',
        agnterCertType: null,
        agnterCretno: '',
        agnterName: '',
        agnterRlts: null,
        agnterTel: '',
        bilgDeptId: null,
        bilgDrId: null,
        bilgOptId: null,
        icdCode: '',
        icdName: '',
        mainRxId: null,
        name: '',
        opspRx: false,
        pricingType: null,
        purcAmt: null,
        reAmt: null,
        regId: null,
        remark: '',
        remarks: '',
        rxFrom: null,
        rxType: null,
        saleAmt: null,
        seeDoctorId: null,
        seeId: null,
        sex: null,
        skintstRx: null,
        state: null,
        dugDrxDetailsVOS: [],
        phayId: null,
        prescriptionAmt: null,
      },
      diagnosisForm: {
        chineseMedicine: '',
        chineseSyndrome: '',
        chineseSyndromeCode: '',
        chineseSyndromeName: '',
        definiteDiagnosis: '',
        diagnosticCategory: '',
        diagnosticName: '',
        diagnosticSequence: '',
        diseaseCode: '',
        diseaseName: '',
        icdCode: '',
        insuranceCode: '',
        insuranceName: '',
        remark: '',
        seeDoctorId: null,
        specialCode: '',
        specialName: '',
        specialNum: '',
        specialRemark: '',
        syndromeCode: '',
        syndromeName: '',
        westernPrefix: '',
        westernSuffix: '',
      },

      active: -1,
      checkedchinaMakeMethod: {},
      checkedchinaPrescriptionId: null,

      showDoseDialog: false,
      isSkinTestDoseDialog: false,
      selExecutionPLDialogVisible: false,
      editDoseValue: 0,
      currentEditIndex: -1,

      loading: false,
      addModalVisible: false,
      isInputDisabled: false,
      isFormExpanded: false,
      celerityFilingDialogVisible: false,
      receptionModalVisible: false,
      sevenDayDialogVisible: false,
      historyMedicalDialogVisible: false,
      creationMethodDialogVisible: false,

      basMednTypeOptions: [{id: 1, label: '国家基药'}, {id: 2, label: '省级基药'}, {id: 3, label: '敌方基药'}],
      seeDoctorStateOption: [{id: 0, label: '禁用'}, {id: 1, label: '就诊'}, {id: 2, label: '取消就诊'}, {
        id: 3,
        label: '转诊'
      }],
      sexOptions: [{id: 1, label: '男'}, {id: 2, label: '女'}],
      skintstDicmOptions: [{id: 0, label: '否'}, {id: 1, label: '是'}],
      drugTypeOptions: [{id: 1, label: '西药'}, {id: 2, label: '成药'}],
      templateStateOption: [{id: 1, label: '启用'}, {id: 0, label: '禁用'}],
      receptionTypeOption: [{id: '1', label: '正常接诊'}, {id: '2', label: '快速接诊'}],
      pregnantOption: [{id: 0, label: '否'}, {id: 1, label: '是'}],
      westPhayOption: [{id: 1, label: '西药房'}],
      chinaPhayOption: [{id: 2, label: '中药房'}],
      
      conerPleasett: '',
      naplPleasett: '',
      addressProps: {
        lazy: true,
        value: 'areaCode',
        label: 'areaName',
        emitPath: true,
        leaf: node => node.areaLevel >= 5,
        lazyLoad: async (node, resolve) => {
          try {
            const level = node.level + 1;

            // 限制最大层级为5
            if (level > 5) {
              return resolve([]);
            }

            // 请求参数
            const params = {
              areaCode: node.level > 0 ? node.data.areaCode : undefined,
              areaLevel: level,
              condtion: ['area_p_code', 'area_p_code', 'area_c_code', 'area_d_code', 'area_t_code'][level - 1]
            };

            const res = await getArea(params);
            const responseData = res?.data || [];

            // 如果没有数据，关闭下拉框
            if (responseData.length === 0 && level > 1) {
              this.handleCloseCascader();
            }

            // 格式化数据（关键修改：添加 isLeaf 和 level 属性）
            const formattedData = responseData.map(item => ({
              ...item,
              value: item.areaCode, // 严格模式需要 value 字段
              label: item.areaName,
              level: level, // 标记当前层级
              isLeaf: level >= 5 // 第五级强制设为叶子节点
            }));

            resolve(formattedData);

          } catch (error) {
            console.error('加载地区数据失败:', error);
            resolve([]);
          }
        }
      },
      
      tableRows1: [
        {name: "健康ID", prop: "patNo", type: ""},
        {name: "姓名", prop: "name", type: ""}, {name: "排", prop: "order", type: ""},
        {name: "时间", prop: "optTime", nz: "nz"}, {name: "诊室", prop: "regDeptName", type: ""},
      ],
      tableRows2: [
        {name: "姓名", prop: "patientName", type: ""},
        {name: "健康ID", prop: "patNo", type: ""},
        {name: "就诊医生", prop: "doctorId", op: 'doctorOptions'},
        {name: "状态", prop: "status", op: 'seeDoctorStateOption'},
        {name: "就诊科室", prop: "regDepId", op: 'deptOptions'},
        {name: "挂号序号ID", prop: "dregisterTableId", type: ""},
      ],
      tableRows3: [
        {name: "就诊序号", prop: "id"}, {name: "患者序号", prop: "patientId", type: ""},
        {name: "姓名", prop: "patientName", type: ""}, {name: "性别", prop: "gender", type: "", op: 'sexOptions'},
        {name: "年龄", prop: "age", type: ""}, {name: "联系地址", prop: "address", type: ""},
        {name: "身份证", prop: "cardid", type: ""}, {name: "挂号类型", prop: "dregisterTableId", type: ""},
        {name: "就诊时间", prop: "createTime", type: ""},
        {name: "就诊类型", prop: "type", op: 'receptionTypeOption'}, {
          name: "就诊医生",
          prop: "doctorId",
          op: 'doctorOptions'
        },
        {name: "是否孕妇", prop: "pregnant", op: 'pregnantOption'},
        {name: "西医诊断", prop: "westernDiagnos", type: ""}, {name: "中医诊断", prop: "chinaDiagnose", type: ""},
        {name: "过敏原", prop: "allergen", type: "", op: 'aiseListOptions'},
        {name: "舒张压", prop: "diapre", type: ""}, {name: "收缩压", prop: "syspre", type: ""},
        {name: "血糖类型", prop: "bloodType", type: "", op: 'bloodTypeOptions'}, {
          name: "血糖指数",
          prop: "bloodNumber",
          type: ""
        },
        {name: "主诉", prop: "patientTell", op: 'visitStateOption'}, {name: "现病史", prop: "nowHistory", type: ""},
        {name: "既往史", prop: "beforeHistory", op: 'visitStateOption'}
      ],
      tableRows4: [
        {name: "临床诊断名称", prop: "name", type: ""},
        {name: "医保编码", prop: "chsCode", type: ""}, {name: "医保名称", prop: "chsName", type: ""},
        {name: "备注", prop: "remarks", type: ""},
      ],
      tableRows8: [
        {name: "临床诊断名称", prop: "name", type: ""}, {name: "确诊", prop: "definiteDiagnosis", type: ""},
        {name: "医保编码", prop: "chsCode", type: ""}, {name: "医保名称", prop: "chsName", type: ""},
      ],
      tableRows5: [
        {name: "编码", prop: "code", type: ""}, {name: "名称", prop: "name", type: ""},
        {name: "医保编码", prop: "chsCode", type: ""}, {name: "医保名称", prop: "chsName", type: ""},
      ],
      tableRows6: [
        {name: "病症名称", prop: "diagnosticName", type: ""}, {name: "病症编码", prop: "diseaseCode", type: ""},
        {name: "证候名称", prop: "chineseSyndromeName", type: ""},
        {name: "证候编码", prop: "chineseSyndromeCode", type: ""}, {
          name: "病症医保名称",
          prop: "insuranceName",
          type: ""
        },
        {name: "病症医保代码", prop: "insuranceCode", type: ""}, {name: "证候医保名称", prop: "syndromeName", type: ""},
        {name: "证候医保代码", prop: "syndromeCode", type: ""},
      ],
      tableRows7: [
        //{name: "基本药物", prop: "basMednB", align: "center", op: 'skintstDicmOptions'},
        //{name: "基药类型", prop: "basMednType", align: "center", op: 'basMednTypeOptions'},
        {name: "西药名称", prop: "drugName", align: "center"},
        /*{name: "包装规格", prop: "pacSpec", align: "center"},*/
        {name: "单位剂量", prop: "unitDose", align: "center"},
        {name: "单次剂量", prop: "sdoseCnt", align: "center"},
        {name: "用药频率", prop: "usedfrquId", align: "center"},
        {name: "周期次数", prop: "prdCnt", align: "center"}, {name: "周期天数", prop: "prdDays", align: "center"},
        {name: "给药方式", prop: "medcWayId", align: "center"},
        {name: "输液速度", prop: "speed", align: "center"},
        /*{name: "药品剂型", prop: "dosform", align: "center", op: 'drugDosageOption'},
        {name: "药品类型", prop: "drugType", align: "center", op: 'drugTypeOptions'},
        {name: "剂量单位", prop: "dosUnt", align: "center", op: 'dosaUntOptions'},
        {name: "药品序号", prop: "drugId", align: "center"},
        {name: "总剂量", prop: "sdoseSum", align: "center"},
        {name: "处方金额", prop: "amount", align: "center"},
        {name: "处方数量", prop: "cnt", align: "center"},
        {name: "销售单位", prop: "saleUntName", align: "center"},
        {name: "取整方式", prop: "roundUnt", align: "center", op: 'roundUntOption'},*/
        /*        {name: "包装单位", prop: "pacUnt", align: "center", op: 'drugUntOptions'},
                {name: "最小单位", prop: "minUnt", align: "center", op: 'drugUntOptions'},*/
        /*{name: "是否皮试", prop: "skintstDicm", align: "center", op: 'skintstDicmOptions'},
        {name: "皮试结果", prop: "skintstRslt", align: "center"},*/
        /*{name: "医嘱嘱托", prop: "remarks", align: "center"},*/
        /* {name: "销售单价", prop: "salePric", align: "center"},
         {name: "销售金额", prop: "saleAmt", align: "center"},
         {name: "最小单位销售单价", prop: "minSalePric", align: "center"},
         {name: "最大单位销售单价", prop: "maxSalePric", align: "center"},
         {name: "成本金额", prop: "purcAmt", align: "center"}, {name: "成本单价", prop: "purcPric", align: "center"},
         {name: "库存数量", prop: "purcCnt", align: "center"},
        {name: "处方类型", prop: "rxType", align: "center", op: 'rxTypeOptions'}*/
      ],
      tableRows9: [
        {name: "序号", prop: "id"},
        {name: "项目名称", prop: "costname"},
        {name: "执行单价", prop: "odcost"},
        {name: "执行价格", prop: "executeOdcost"},
        {name: "执行频率", prop: "exeFrquId", op: 'medicationFrequencyOptions'},
        {name: "开单医生", prop: "doctorName", op: 'doctorOptions'},
        {name: "执行科室", prop: "deptName", op: 'deptOptions'},
        {name: "备注", prop: "remark"},
      ],
      tableRows10: [
        {name: "类型", prop: "orderType", op: 'orderTypeOptions'},
        {name: "状态", prop: "status", op: 'doctorAdviceTypeOptions'},
         {name: "医嘱内容", prop: "content"},
        {name: "金额", prop: "pric"},
        {name: "开单医生", prop: "createName"},
        {name: "开单时间", prop: "createTime"},
        /*{name: "打印状态", prop: "print", op: 'printTypeOptions'},*/
        {name: "执行科室", prop: "deptId", op: 'deptOptions'},
        //{name: "国家贯标编码", prop: "nationState"},
        //{name: "国家贯标名称", prop: "nationName"},
      ],
      tableRows11: [
        {name: "库存数量", prop: "purcCnt", align: "center"},
        {name: "药品序号", prop: "drugId", align: "center"},
        /*{name: "基本药物", prop: "basMednB", align: "center", op: 'skintstDicmOptions'},*/
        /*{name: "基药类型", prop: "basMednType", align: "center", op: 'basMednTypeOptions'}, */
        {
          name: "西药名称",
          prop: "drugName",
          align: "center"
        },
        {name: "药品规格", prop: "drugSpec", align: "center"}, {
          name: "药品剂型",
          prop: "dosform",
          align: "center",
          op: 'drugDosageOption'
        },
        {name: "药品类型", prop: "drugType", align: "center", op: 'drugTypeOptions'}, {
          name: "单位剂量",
          prop: "unitDose",
          align: "center",
        }, {name: "剂量单位", prop: "dosUnt", align: "center",},
        {name: "最小剂量", prop: "minDose", align: "center", op: 'dosaUntOptions'},
        {name: "是否皮试", prop: "skintstDicm", align: "center", op: 'skintstDicmOptions'},
        {name: "有效日期", prop: "expyDate", align: "center"}, {name: "冻结数量", prop: "freezeCnt", align: "center"},
        {name: "生产日期", prop: "manuDate", align: "center"}, {name: "生产批号", prop: "manuLotnum", align: "center"},
        {name: "最大单位成本单价", prop: "maxPurcPric", align: "center"}, {
          name: "最大单位零售单价",
          prop: "maxSalePric",
          align: "center"
        },
        {name: "最小单位成本单价", prop: "minPurcPric", align: "center"}, {
          name: "最小单位零售单价",
          prop: "minSalePric",
          align: "center"
        },
        {name: "包装数量", prop: "pacCnt", align: "center"}, {name: "包装规格", prop: "pacSpec", align: "center"},
        {name: "包装单位", prop: "pacUnt", align: "center", op: 'drugUntOptions'}, {
          name: "暂停使用",
          prop: "pauseB",
          align: "center",
          op: 'skintstDicmOptions'
        },
        {name: "药房", prop: "phayId", align: "center", op: 'deptOptions'}, {
          name: "生产厂家",
          prop: "prodentpName",
          align: "center"
        },
        {name: "成本金额", prop: "purcAmt", align: "center"},
        {name: "成本单价", prop: "purcPric", align: "center"}, {
          name: "库存类型",
          prop: "purcType",
          align: "center",
          op: 'saleUntOption'
        },
        {name: "销售金额", prop: "saleAmt", align: "center"}, {name: "销售单价", prop: "salePric", align: "center"},
      ],
      tableRows12: [
        {name: "药品序号", prop: "drugId", type: ""},
        {name: "药品名称", prop: "drugName", type: ""},
        {name: "库存数量", prop: "purcCnt", type: ""},
        {name: "库存类型", prop: "purcType", type: "", op: 'saleUntOption'},
        {name: "最大单位成本单价", prop: "maxPurcPric", type: ""},
        {name: "最大单位销售单价", prop: "maxSalePric", type: ""},
        {name: "最小单位成本单价", prop: "minPurcPric", type: ""},
        {name: "最小单位销售单价", prop: "minSalePric", type: ""},
        {name: "销售金额", prop: "saleAmt", type: ""},
        {name: "销售单价", prop: "salePric", type: ""},
        {name: "成本金额", prop: "purcAmt", type: ""},
        {name: "成本单价", prop: "purcPric", type: ""},
        {name: "国家贯标名称", prop: "chsName", type: ""},
        {name: "国家贯标编码", prop: "purcDate", type: ""},
        {name: "药品类型", prop: "tcmtype", type: ""},
        {name: "供货单位", prop: "supplyName", type: "", op: 'deptOptions'},
      ],
      tableRows14: [
        {name: "健康ID", prop: "id"},
        {name: "健康卡号", prop: "patId"},
        {name: "姓名", prop: "name"},
        {name: "身份证号", prop: "certno"},
        {name: "联系电话", prop: "conerTel"},
      ],
      tableRows15: [
        {name: "系统序号", prop: "id"},
        {name: "就诊序号", prop: "seeDoctorId"},
        {name: "患者名称", prop: "patientName"},
        {name: "诊所名称", prop: "clinicName"},
        {name: "创建时间", prop: "createTime"},
        {name: "主诉", prop: "patientTell"},
        {name: "现病史", prop: "nowHistory"},
        {name: "既往史", prop: "beforeHistory"},
      ],

      selChineseMedicineDialog: false,
      westernDiagnosisModalVisible: false,
      chinaDiagnosisModalVisible: false,
      selWestMedicineDialog: false,
      selDoctordisposeDialog: false,
      chinaMedicineTableData: [],
      westMedicineTableData: [],
      westGroupsTableData: [],
      queryWestMedicineData: [],
      queryChinaMedicineData: [],
      doctordisposeTableData: [],
      medicalAdviceData: [],
      tableData: [],

      prhCostOption: [],//病员费别
      prhTypeOption: [],//病员类别
      rltsEntitiesOption: [],//联系人关系
      contractUnitOption: [],//合约单位
      untAtteOption: [],//往来单位新增---单位属性
      deptOptions: [],//科室下拉框
      doctorOptions: [],//医生下拉框
      registerOptions: [],//挂号类别
      ntlyOptions: [],//国籍
      aiseListOptions: [],//过敏原
      chinaMakeOptions: [],//中药制法
      tcmwayOptions: [],//中药服法
      tableData1: [],
      tableData2: [],
      // 表单数据
      seedoctorQueryParams: {
        patientName: '',
        patientId: '',
        startTime: dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
        endTime: dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
        doctorId: null,
        timeFrame: 0,
      },

      showPatientTellSelect: false,
      showNowHistorySelect: false,
      showBeforeHistorySelect: false,

      tpAddOrEditMedicineDialog: false,
      templateAddRrEditTtiel: '',
      aiseAddRrEditTtiel: '',
      aiseAddOrEditMedicineDialog: false,
      templateType: null,


      templateRules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 1, max: 50, message: '长度在1到50个字符', trigger: 'blur'}
        ],
        deptId: [
          {required: true, message: '请选择科室', trigger: 'change'}
        ],
        rangeType: [
          {required: true, message: '请选择适用范围', trigger: 'change'}
        ],
        state: [
          {required: true, message: '请选择状态', trigger: 'change'}
        ],
        content: [
          {required: true, message: '请输入内容', trigger: 'blur'},
          {min: 1, max: 500, message: '长度在1到500个字符', trigger: 'blur'}
        ],
      },
      aiseRules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 1, max: 50, message: '长度在1到50个字符', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '请选择类型', trigger: 'change'}
        ],

      },
      aiseForm: {
        id: null,
        code: '',
        name: '',
        orderId: null,
        pyCode: '',
        remark: '',
        state: 1,
        type: null,
      },
      templateForm: {
        id: null,
        content: '',
        deptId: null,
        name: '',
        pinyin: '',
        rangeType: null,
        remark: '',
        state: 1,
      },
      fastReceptionForm: {
        patId: '',
        name: '',
        sex: '1',
        identityCard: 1,
        certno: '',
        brdy: '',
        naty: null,
        ageYear: null,
        ageMonth: null,
        jobId: null,
        feeType: null,
        prhType: null,
        contractUnit: null,
        conerName: '',
        conerTel: '',
        conerRltsId: null,
        origoProvince: '',       // 省
        origoCity: '',           // 市
        origoCounty: '',         // 县
        origoTown: '',           // 乡
        origoVillage: '',         //村
        contactProvince: '',       // 省
        contactCity: '',           // 市
        contactCounty: '',         // 县
        contactTown: '',           // 乡
        contactVillage: '',         //村
        price: null,
        regTypeId: null,
        naplAddName: null,
        prhCostType: null,
      },
      receptionForm: {
        address: '',
        age: null,
        allergen: '',
        beforeHistory: '',
        bloodNumber: '',
        bloodPressure: '',
        bloodType: '',
        cardid: '',
        chinaDiagnose: '',
        chronicDisease: '',
        diagnosisAdvice: '',
        doctorId: null,
        epidemicDisease: '',
        gatherMorbidity: '',
        gender: '',
        goHigharea: '',
        nowHistory: '',
        patientId: null,
        patientName: '',
        patientTell: '',
        price: null,
        regTypeId: null,
        regTypeName: '',
        westernDiagnos: '',
        status: null,
      },
      addSeedoctorForm: {
        address: '',
        age: null,
        allergen: '',
        beforeHistory: '',
        bloodNumber: null,
        bloodPressure: '',
        bloodType: '',
        cardid: '',
        chinaDiagnose: '',
        chronicDisease: '',
        diagnosisAdvice: '',
        doctorId: null,
        dregisterTableId: null,
        epidemicDisease: '',
        gatherMorbidity: '',
        gender: '',
        goHigharea: '',
        nowHistory: '',
        patientId: null,
        patientName: '',
        price: null,
        patientTell: '',
        westernDiagnos: '',
        remark: '',
        chinaPrescription: '',
        westchinaPrescription: '',
        doctordisposePrescription: '',
      },

      recordingList: [],
      showRecordingModal: false,
      showRecordingModalData: false,
      chinaMedicineUsageDialog: false,
      isRecording: false,
      audioBlob: null,  // 保留用于上传
      audioChunks: [],  // 保留用于生成Blob
      recordingTime: '00:00',
      recordingTimer: null,
      stream: null,
      mediaRecorder: null,

      recordingListOptions: [],
      currentAudioPath: '',
      activeIndex: null,

      contextMenu: {
        visible: false,
        left: 0,
        top: 0,
        field: ''
      },
      addUnitForm: {
        id: null,
        code: '',
        state: 1,
        area: 1,
        name: '',
        pyCode: '',
        bankName: '',
        bankNo: '',
        splerPmtno: '',
        legalRepe: '',
        mainConer: '',
        conerPhone: '',
        conerTel: '',
        conerQq: '',
        conerFax: '',
        conerPostc: '',
        url: '',
        conerMail: '',
        untAtte: 3,
        uscc: '',
        conerAdd: '',
        remark: ''
      },
      addUnitType: [],
      addType: [],
      nationOption: [],//民族下拉框
      certypeOption: [],//证件下拉框
      profttlOption: [],//职业下拉框
      jobOption: [],//职业下拉框

      chargingPriceOptions: [],//西医模板下拉框
      complainTemplateOptions: [],//主诉模板
      nowHistoryTemplateOptions: [],//现病史模板
      beforeHistoryTemplateOptions: [],//既往史模板
      medicationWayOptions: [],//给药方式
      mrgStateOptions: [],//婚姻状态
      chinaMedicationWayOptions: [],//中药给药方式
      medicationFrequencyOptions: [],//给药频率
      dosaUntOptions: [],//单位剂量、最小单位
      drugUntOptions: [],//包装单位
      drugDosageOption: [],//药品剂型

      currentSelectedRow: null,

      repeatedOptions: [{id: 1, label: '复诊'}, {id: 2, label: '初诊'}],

      takeMedicineWayOptions1: [
        {id: 1, label: '频服'}, {id: 2, label: '冷服'}, {id: 3, label: '顿服'},
        {id: 4, label: '温服'}, {id: 5, label: '热服'}
      ],
      takeMedicineWayOptions2: [
        {id: 1, label: '饭后服'}, {id: 2, label: '隔夜服'},
        {id: 3, label: '空腹服'}, {id: 4, label: '睡前服'},
        {id: 5, label: '饭前服'}, {id: 6, label: '餐间服'}
      ],

      rxTypeOptions: [],
      rangeTypeOption: [{id: 1, label: '本人'}, {id: 2, label: '本科室'}],
      aiseTypeOption: [{id: 1, label: '药品'}, {id: 2, label: '其他'}],
      saleUntOption: [{id: 1, label: '最小单位'}, {id: 2, label: '包装单位'}],
      roundUntOption: [{id: 1, label: '单次取整'}, {id: 2, label: '总量取整'}, {id: 3, label: '处方取整'}, {
        id: 4,
        label: '不取整'
      }],
      extgTypeOption: [{id: 0, label: '人工煎药'}, {id: 1, label: '煎药机煎药'}],
      orderTypeOptions: [{id: 0, label: '西药'}, {id: 1, label: '中药'},
        {id: 2, label: '检查'}, {
          id: 3, label: '检验'
        }, {id: 4, label: '处置'}, {id: 5, label: '挂号'}, {id: 6, label: '关联处置'}],
      printTypeOptions: [{id: 0, label: '否'}, {id: 1, label: '是'}],
      doctorAdviceTypeOptions: [{id: 0, label: '待发'}, {id: 1, label: '已发送'}, {id: 2, label: '已收款'}, {
        id: 3,
        label: '锁定'
      }, {id: 4, label: '已退费'}, {id: 5, label: '已作废'}],
      patientChooseForm: {
        id: null,
        patId: '',
        name: '',
        sex: null,
        certno: null,
        conerTel: null,
        contractUnit: null,
        healthCardNo: null,
        cardType: null,
        seeDoctorId: null,
        repeated: null,
      },
      addForm: {
        discountMoney: null,
        name: '',
        patientId: null,
        payType: null,
        receivableMoney: null,
        receivedMoney: null,
        regDepId: null,
        regDoctorId: null,
        regMode: null,
        regNum: null,
        regTypeId: null,
        regUserId: null,
        remake: '',
        utyTimeDetailsId: null,
        visitId: null,
        rgstId: null,
        /**/
        accountNumber: null,
        currentNumber: null,
        oweNumber: '0/0',
        remark: null,
        feeType: null,
        MoneyPay: null,
        healthCarePay: null,
        fitnessCardpa: null,
        unionPay: null,
        owePay: null,
        phonePay: null,
        discountsNumb: null,
        receivableNum: null,
        receiveNumber: null,
        changeNumber: null,
      },
      addUnitModalVisible: false, // 布尔值，控制模态框显示
      isShowPrescription: false,

      mobileRegExp: /^1[3-9]\d{9}$/,
      patientFormRules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'change'}
        ],
        tel: [
          {
            validator: (rule, value, callback) => {
              // 如果 thrNot 为 1，直接跳过验证
              if (this.patientForm.thrNot === 1) {
                callback();
                return;
              }
              if (!value) {
                callback();
                return;
              }
              if (!this.mobileRegExp.test(value)) {
                callback(new Error('请输入正确的手机号格式'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      },
      patientFormDataRules: {
        certno: [
          {
            validator: async (rule, value, callback) => {
              if (!this.patientForm.thrNot === this.patientForm.ageYear < 18) return callback();
              if (!value) return callback();

              const type = this.patientForm.identityCard;

              // 基础验证
              if (value.length !== this.certLengthMap[type]) {
                return callback(new Error(`请输入${this.certLengthMap[type]}位证件号码`));
              }

              if (this.certPatterns[type] && !this.certPatterns[type].test(value)) {
                return callback(new Error('证件号码格式不正确'));
              }

              // 仅身份证需要查重
              if (type === '1') {
                try {
                  const res = await getDoesItExistSFZ({
                    certNo: value.toString()
                  });

                  if (res.data && value !== this.patientChooseForm?.certno) {
                    return callback(new Error('该身份证已存在')); // 非阻塞提示
                  }
                } catch (error) {
                  console.error('身份证校验失败:', error);
                  // 接口失败不影响基础验证
                }
              }

              callback();
            },
            trigger: 'blur'
          }
        ],
        bloodPressure: [
          {
            validator: (rule, value, callback) => {
              // 跳过条件：三无人员或年龄小于18岁
              if (this.patientForm.thrNot === 1 || this.patientForm.ageYear < 18) {
                return callback();
              }

              // 初始加载跳过验证
              if (this.isInitialLoad) {
                this.$nextTick(() => {
                  this.isInitialLoad = false;
                });
                return callback();
              }

              // 血压值超长处理（保留基本格式校验）
              if (this.patientForm.syspre && this.patientForm.syspre.toString().length > 3) {
                this.patientForm.syspre = null;
                return callback(new Error('收缩压值过长（最多3位数字）'));
              }
              if (this.patientForm.diapre && this.patientForm.diapre.toString().length > 3) {
                this.patientForm.diapre = null;
                return callback(new Error('舒张压值过长（最多3位数字）'));
              }

              // 宽松的数字格式校验
              const validateNumber = (val, fieldName) => {
                if (val && !/^\d{1,3}$/.test(val.toString())) {
                  return callback(new Error(`${fieldName}必须是1-3位数字`));
                }
              };
              callback();
            },
            trigger: 'blur'
          }
        ],
        bloodNumber: [
          {
            validator: (rule, value, callback) => {
              // 跳过条件：三无人员或年龄<18
              if (this.patientForm.thrNot === 1 || this.patientForm.ageYear < 18) {
                return callback();
              }

              // 初始加载跳过验证
              if (this.isInitialLoad) return callback();

              // 血糖值超长处理
              if (value && String(value).replace('.', '').length > 2) {
                this.patientForm.bloodNumber = null;
                return callback(new Error('请输入合理血糖值'));
              }

              // 格式验证
              if (value && !/^\d+(\.\d{1})?$/.test(value)) {
                return callback(new Error('格式如: 5.6'));
              }

              // 范围提示（非阻塞）
              if (value) {
                const num = parseFloat(value);
                if (num < 3.9 || num > 11.1) {
                  this.$message.warning('血糖值超出正常范围（3.9-11.1）');
                }
              }

              callback();
            },
            trigger: 'blur'
          }
        ],
        conerTel: [
          {
            validator: (rule, value, callback) => {
              if (!this.patientForm.thrNot === 1) return callback();
              if (!value) return callback();
              const mobileReg = /^1[3-9]\d{9}$/;
              const telReg = /^0\d{2,3}-\d{7,8}$/;

              if (!mobileReg.test(value) && !telReg.test(value)) {
                return callback(new Error('请输入正确号码'));
              }
              callback();
            },
            trigger: 'blur'
          }
        ]
      },
      westSonData: {},
      patientForm: {
        id: null,
        patId: '',       // 健康ID
        thrNot: null,   // 三无（复选框应为布尔值）
        name: '',           // 姓名
        sex: null,       // 性别
        identityCard: 1,
        certno: '',   //证件号码
        brdy: '',      // 出生日期
        ageYear: null,        // 年龄-岁
        ageMonth: null,       // 年龄-月
        naty: 1,     // 民族
        ntlyId: 1,     // 国籍
        jobId: null,            // 职业
        prhCostType: null, // 病员费别
        prhType: null, // 病员类型
        phrUnt: null,  // 合约单位
        isSpecial: '否',    // 特殊人群
        conerName: '',        // 联系人
        conerTel: '',          // 联系电话
        conerRltsId: null, // 联系人关系
        province: '',       // 省
        city: '',           // 市
        county: '',         // 县
        town: '',           // 乡
        village: '',         //村
        registerDate: new Date().toISOString().split('T')[0],   // 挂号日期
        timeSlot: '1',       // 时段
        department: null,     // 科室
        doctor: null,         // 医生
        registerType: null,   // 挂号类别
        clinicRoom: null,  // 诊室
        existNumber: null,
        currentNumber: null,
        caseHistory: null,
        total: null,
        naplAddCode: null,
        number: null,
        aiseId: null,
        aiseName: null,
        seedoctorcCount: null,
        seedoctorcType: null,
        attackTime: new Date().toISOString().split("T")[0],
        bloodType: '1',
        bloodNumber: null,
        systolicPressure: "收缩压",
        diastolicPressure: "舒张压",
        contactProvince: '',       // 省
        contactCity: '',           // 市
        contactCounty: '',         // 县
        contactTown: '',           // 乡
        contactVillage: '',         //村
        conerAddCode: '',
        naplAddName: '',
        conerAddName: '',
        dregisterTableId: null,
        opspRx: false,
        diapre: null,
        syspre: null,
        conerAddCodeArr: [],
        naplAddCodeArr: [],
        tel: '',
        conerAddJoinName: '',
        pregnant: null,
        repeated: null,
      },
      celerityFilingForm: {
        name: '',           // 姓名
        sex: null,       // 性别
        identityCard: 1,
        certno: '',   //证件号码d
        brdy: '',      // 出生日期
        ageYear: 0,        // 年龄-岁
        ageMonth: 0,       // 年龄-月
        ageDay: 0,       // 年龄-天
        naty: 1,     // 民族
        ntlyId: 1,    //国籍
        jobId: '',            // 职业
        prhType: null, // 病员类型
        contractUnit: null,  // 合约单位
        conerName: '',        // 联系人
        conerTel: '',          // 联系电话
        conerRltsId: null, // 联系人关系
        province: '',       // 省
        city: '',           // 市
        county: '',         // 县
        town: '',           // 乡
        village: '',         //村
        tel: null,
        restAddCode: null,
        naplAddCode: null,
      },
      addUnitRules: {
        code: [{required: true, message: '请填写合约单位编码！', trigger: 'change'}],
        name: [{required: true, message: '请填写合约单位名称！', trigger: 'change'}],
      },
      permissionsArr: [],

      checkChianData: [],
      multipleActiveSelection: [],

      //右键接诊数据
      showReception: false,
      showChinaReception: false,
      showCancelReception: false,
      showAdviceRightClick: false,
      showWestGroupsClick: false,
      adviceRightClickRow: null,
      chinaReceptionRowData: null,
      ReceptionRowData: null,
      contextMenuLeft: 0,
      contextMenuTop: 0,
    };
  },
  computed: {
    medicineSearchQuery: {
      get() {
        return this.DropDownedName === '西药医嘱'
            ? this.westMedicineSearchQuery
            : this.chinaMedicineSearchQuery;
      },
      set(value) {
        if (this.DropDownedName === '西药医嘱') {
          this.westMedicineSearchQuery = value;
        } else {
          this.chinaMedicineSearchQuery = value;
        }
      }
    },
    // 分页数据计算
    pagedWestMedicineData() {
      const start = (this.westPagination.currentPage - 1) * this.westPagination.pageSize
      const end = start + this.westPagination.pageSize
      return this.queryWestMedicineData.slice(start, end)
    },

    pagedChinaMedicineData() {
      const start = (this.chinaPagination.currentPage - 1) * this.chinaPagination.pageSize
      const end = start + this.chinaPagination.pageSize
      return this.queryChinaMedicineData.slice(start, end)
    },
    formattedAudioUrl() {
      if (!this.currentAudioPath) return '';
      // 将反斜杠转换为正斜杠
      let url = this.currentAudioPath.replace(/\\/g, '/');
      // 如果没有协议，添加http协议
      if (!/^https?:\/\//.test(url)) {
        url = `http://${url}`;
      }
      return url;
    },
    isSyspreInvalid() {
      return this.patientForm.syspre && (this.patientForm.syspre < 90 || this.patientForm.syspre > 140);
    },
    isDiapreInvalid() {
      return this.patientForm.diapre && (this.patientForm.diapre < 60 || this.patientForm.diapre > 90);
    },
    isBloodNumberInvalid() {
      if (!this.patientForm.bloodNumber) return false;
      return this.patientForm.bloodNumber < 3 || this.patientForm.bloodNumber > 12;
    }
  },
  watch: {
    westMedicineTableData: {
      handler(newVal) {
        if (!this.patientChooseForm?.seeDoctorId) return;

        // 即使数组为空，仍然序列化
        const westJson = JSON.stringify(this.westMedicineTableData);
        const chinaJson = JSON.stringify(this.chinaMedicineTableData);

        // 组装数据（即使两个数组都为空）
        const dataToSave = {
          west: westJson,
          china: chinaJson
        };

        // 始终发送请求（即使两个数组都为空）
        addMedicineCache({
          seeDoctorId: this.patientChooseForm.seeDoctorId,
          data: JSON.stringify(dataToSave)
        });
      },
      deep: true
    },
    chinaMedicineTableData: {
      handler(newVal) {
        if (!this.patientChooseForm?.seeDoctorId) return;

        // 即使数组为空，仍然序列化
        const westJson = JSON.stringify(this.westMedicineTableData);
        const chinaJson = JSON.stringify(this.chinaMedicineTableData);

        // 组装数据（即使两个数组都为空）
        const dataToSave = {
          west: westJson,
          china: chinaJson
        };

        // 始终发送请求（即使两个数组都为空）
        addMedicineCache({
          seeDoctorId: this.patientChooseForm.seeDoctorId,
          data: JSON.stringify(dataToSave)
        });
      },
      deep: true
    }
  },
  beforeDestroy() {
    window.removeEventListener('keydown', this.handleKeyPress);
  },
  async mounted() {
    await withLoading(this, '正在初始化...')(async () => {
      // 1. 同步操作前置
      this.addUnitType = [...AddType];
      this.addType = [...AddType2];
      this.permissionsArr = JSON.parse(localStorage.getItem('permissions') || '[]');
      this.userInfo = JSON.parse(localStorage.getItem("userInfo") || '{}');
      this.westAddForm = westAddForm[0];

      // 2. 并行优化：将独立请求并行化
      const [userPermission, ...apiResults] = await Promise.all([
        getStaff({id: this.userInfo.staffId}),
        this.loadData(),
        this.getDeptList(),
        this.getDoctorList(),
        this.getContuntList(),
        this.getAiseList(),
        this.getMedicationFrequency(),
        this.dict(),
        this.getChargingPrice(),
        this.selectDrugDosageForm(),
        this.getDosaUnt()
      ]);

      // 3. 避免重复请求（原代码中有重复的 getMedicationFrequency）
      this.userPermission = userPermission?.data;

      // 4. 事件监听优化：使用 passive 事件提高滚动性能
      this.$nextTick(() => {
        window.addEventListener('keydown', this.handleKeyPress, { passive: true });
        document.addEventListener('click', this.handleClickOutside);
      });
    });
  },
  methods: {
    validateBloodNumber() {
      if (this.isBloodNumberInvalid) {
        this.$message.warning(`血糖值 ${this.patientForm.bloodNumber} mmol/L 超出正常范围(3-12)`);
      }
    },

    validateBloodPressure() {
      if (this.isSyspreInvalid) {
        this.$message.warning(`收缩压值 ${this.patientForm.syspre} 超出正常范围(90-140)`);
      }
      if (this.isDiapreInvalid) {
        this.$message.warning(`舒张压值 ${this.patientForm.diapre} 超出正常范围(60-90)`);
      }

      // 如果两个都超出范围，只显示一条合并提示
      if (this.isSyspreInvalid && this.isDiapreInvalid) {
        this.$message.warning(`血压值超出正常范围(收缩压:90-140, 舒张压:60-90)`);
      }
    },

    validateTel(fieldName) {
      const phoneNumber = this.patientForm[fieldName];

      // 如果为空则不验证（根据需求可以调整为必填）
      if (!phoneNumber) return true;

      // 中国大陆手机号正则
      const phoneRegex = /^1[3-9]\d{9}$/;

      if (!phoneRegex.test(phoneNumber)) {
        const fieldLabel = fieldName === 'tel' ? '联系电话' : '联系人电话';
        this.$message.warning(`${fieldLabel}格式不正确，请输入11位中国大陆手机号`);
        return false;
      }
      return true;
    },

    preVerificationUserInfo() {
      if (this.patientForm.id === null) {
        this.$message.warning("请选择患者后进行操作");
        return false;
      }

      if (!this.patientForm.syspre) {
        this.$refs.syspreRef.focus();
        this.$message.warning("请填写收缩压信息");
        return false;
      }

      if (!this.patientForm.diapre) {
        this.$refs.diapreRef.focus();
        this.$message.warning("请填写舒张压信息");
        return false;
      }

      if (this.patientForm.ageYear >= 35 && !this.patientForm.bloodNumber) {
        this.$refs.bloodNumberRef.focus();
        this.$message.warning("请填写血糖值");
        return false;
      }

      return true;
    },

    preVerificationUserMedical() {
      if (!this.addSeedoctorForm.patientTell) {
        this.$message.warning("请填写主诉")
        return false;
      }
      if (!this.addSeedoctorForm.beforeHistory) {
        this.$message.warning("请填写既往史")
        return false;
      }
      return true;
    },

    async handleRecordingModalData() {
      await this.getMedicalAudioList();
      this.showRecordingModalData = true;
    },

    async handleConfirmMedicalAdvice() {
      if (this.westMedicineTableData.length > 0) {
        await this.handleConfirmWest();
      }

      if (this.chinaMedicineTableData.length > 0) {
        this.filterChinaMedicationWay();
        this.getChinaDosageSum();
        this.chinaMedicineUsageDialog = true;
      }

    },

    handleTableRowClick(row, column, event) {
      if (this.DropDownedName === '西药医嘱') {
        this.handleSelWestTableRowClick(row, column, event);
      } else {
        this.handleSelChinaTableRowClick(row, column, event);
      }
    },

    async handleCommand(command) {
      this.DropDownedName = command === 'a' ? '西药医嘱' : '中药医嘱';
      if (command === 'a') {
        this.sortGroupedRows();
        this.$nextTick(() => {
          this.renderGroupFlags();
          this.$refs.westMedicineTableData.clearSelection();
        });
      }
    },

    async handleClearDisposeToTag(tag) {
      await this.$confirm(
          `确认删除:【${tag.costname}】处置项目吗?`,
          '删除',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }
      );
      try {
        const res = await delOneAdvice({
          id: this.medicalAdviceData.find(item => item.orderTypeId === tag.id)?.id
        })
        if (res.code === 200) {
          const res2 = await getDoctordispose({seeDoctorId: this.patientChooseForm.seeDoctorId});
          this.doctordisposeTableData = res2.data.map(item => ({
            ...item,
            odcost: item.executionPrice,
            executeOdcost: item.executionAmount,
            doctorName: item.staffId,
            deptName: item.executDeptId,
            count: item.num
          }));
          await this.resetWestMedicineData();
        }
      } catch (error) {
        this.$message.error("系统异常:请联系管理员!!!")
      } finally {

      }
    },

    async handleGetMedicalKeywordList(type) {
      if (!this.preVerificationUserInfo()) return;
      try {
        // 设置当前活动字段
        this.activeField = type === 1 ? 'patientTell' :
            type === 2 ? 'nowHistory' : 'beforeHistory';

        // 获取API数据
        const res = await getSeeDoctorKeywordList({type});

        // 清空原有关键词
        this.keywordGroups[this.activeField].forEach(group => {
          group.keywords = [];
        });

        // 将API数据分配到对应分组
        res.data.forEach(item => {
          let groupType;
          if (type === 1) groupType = item.mainGroup;
          else if (type === 2) groupType = item.nowHistoryGroup;
          else groupType = item.beforeHistoryGroup;

          const targetGroup = this.keywordGroups[this.activeField]
              .find(g => g.type === groupType);

          if (targetGroup) {
            targetGroup.keywords.push(item.name);
          }
        });

        // 默认选中第一个分组
        if (this.keywordGroups[this.activeField].length > 0) {
          this.activeGroup = this.keywordGroups[this.activeField][0].type;
        }

        this.keywordsVisible = res.data.length > 0;
      } catch (error) {
        console.error('获取关键词失败:', error);
        this.keywordsVisible = false;
      }
    },

    addKeyword(word) {
      if (!this.activeField) return;

      const inputEl = document.querySelector(`[data-field="${this.activeField}"]`);
      if (!inputEl) return;

      const value = this.addSeedoctorForm[this.activeField] || '';
      
      // 如果当前字段有值，则以逗号拼接；如果是空串，则直接赋值
      if (value && value.trim() !== '') {
        this.addSeedoctorForm[this.activeField] = value + ',' + word;
      } else {
        this.addSeedoctorForm[this.activeField] = word;
      }

      // 保持关键词面板可见
      this.keywordsVisible = true;

      // 重置光标位置到末尾
      this.$nextTick(() => {
        inputEl.focus();
        const newValue = this.addSeedoctorForm[this.activeField];
        inputEl.setSelectionRange(newValue.length, newValue.length);
      });
    },

    handleClickOutside(e) {
      if (e.target.closest('.keywords-panel')) {
        return;
      }
      const isTargetInput = e.target.closest(`
    [data-field="patientTell"],
    [data-field="nowHistory"],
    [data-field="beforeHistory"]
  `);
      if (!isTargetInput) {
        setTimeout(() => this.keywordsVisible = false, 200);
      }
    },

    handleAllFieldClick({patientTell, nowHistory, beforeHistory}) {
      Object.assign(this.addSeedoctorForm, {patientTell, nowHistory, beforeHistory});
      this.showRecordingModalData = false;
      this.$message.success('引用成功');
    },

    handleFieldClick(text, field) {
      const fieldMessages = {
        patientTell: '主诉内容已更新',
        nowHistory: '现病史内容已更新',
        beforeHistory: '既往史内容已更新'
      };

      if (field in this.addSeedoctorForm) {
        this.addSeedoctorForm[field] = text;
        this.$message.success(fieldMessages[field]);
      }
    },

    handleMenuSelect(index) {
      this.activeIndex = index;
    },

    handleAudioItemClick(audioPath) {
      this.currentAudioPath = audioPath;
      // 自动播放选中的音频
      this.$nextTick(() => {
        const audioElement = this.$refs.audioPlayer;
        if (audioElement) {
          audioElement.play().catch(error => {
            this.$message.warning('音频播放失败：' + error.message);
            console.error('播放错误：', error);
          });
        }
      });
    },

    async getMedicalAudioList() {
      const ctx = this;
      try {
        const res = await getMedicalAudioList({seeDoctorId: ctx.patientChooseForm.seeDoctorId});
        if (res?.code !== 200 || !Array.isArray(res.data)) throw new Error(res?.message || 'Invalid data');

        const options = [], list = [];
        const {clinicName} = ctx.userInfo, {name: patientName} = ctx.patientForm;

        res.data.forEach((item, i) => {
          options.push({index: String(i), name: `系统序号:${item.id}`, audioPath: item.audioPath});
          list.push({...item, clinicName, patientName});
        });

        ctx.recordingListOptions = options;
        ctx.recordingList = list;
      } catch (e) {
        ctx.recordingListOptions = [];
        console.error('Recording load failed:', e);
        ctx.$message.error(`获取失败: ${e.message}`);
      }
    },
    // 开始录音
    startRecording() {
      this.isRecording = true;
      this.audioUrl = '';
      this.audioBlob = null;
      this.audioChunks = [];
      this.startRecordingTimer();

      navigator.mediaDevices.getUserMedia({audio: true})
          .then(stream => {
            this.stream = stream;
            this.mediaRecorder = new MediaRecorder(stream);

            this.mediaRecorder.ondataavailable = (e) => {
              this.audioChunks.push(e.data);
            };

            this.mediaRecorder.onstop = () => {
              this.audioBlob = new Blob(this.audioChunks, {type: 'audio/wav'});
              this.audioUrl = URL.createObjectURL(this.audioBlob);
            };

            this.mediaRecorder.start();
          })
          .catch(error => {
            this.isRecording = false;
            this.stopRecordingTimer();
            this.$message.error(`录音初始化失败: ${error.message || '无法访问麦克风'}`);
          });
    },

    // 停止录音
    stopRecording() {
      if (this.isRecording) {
        this.isRecording = false;
        this.stopRecordingTimer();

        if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
          this.mediaRecorder.stop();
        }
        if (this.stream) {
          this.stream.getTracks().forEach(track => track.stop());
          this.stream = null;
        }

        // 无预览时直接保存（添加此行）
        setTimeout(() => this.saveRecording(), 500);
      }
    },

    // 保存录音并上传
    saveRecording() {
      if (this.audioBlob) {
        this.uploadRecording(this.audioBlob);
        this.showRecordingModal = false;
      } else {
        this.$message.warning('没有可保存的录音数据');
      }
    },

    // 上传录音到后端
    async uploadRecording(blob) {
      await withLoading(this, '录音处理中...')(async () => {
        const formData = new FormData();
        formData.append('file', blob, `recording_${new Date().getTime()}.wav`);

        try {
          const res = await uploadFile(formData);

          if (res && res.code === 200) {
            this.$message.success('录音上传成功');
            const newItem = {
              audioPath: res.data.path,
              patientId: this.patientChooseForm.id,
              seeDoctorId: this.patientChooseForm.seeDoctorId,
            }
            await addMedicalAudio(newItem);
          } else {
            this.$message.error(`录音保存失败: ${res?.message || '未知错误'}`);
          }
        } catch (error) {
          this.$message.error(`上传失败: ${error.message || '网络错误'}`);
        }
      });
    },

    // 录音计时器
    startRecordingTimer() {
      let seconds = 0;
      this.recordingTimer = setInterval(() => {
        seconds++;
        const minutes = Math.floor(seconds / 60);
        this.recordingTime = `${minutes.toString().padStart(2, '0')}:${(seconds % 60).toString().padStart(2, '0')}`;
      }, 1000);
    },

    // 停止计时器
    stopRecordingTimer() {
      clearInterval(this.recordingTimer);
      this.recordingTimer = null;
      this.recordingTime = '00:00';
    },

    // 组件销毁时清理资源
    beforeDestroy() {
      if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
        this.mediaRecorder.stop();
      }
      if (this.stream) {
        this.stream.getTracks().forEach(track => track.stop());
      }
      if (this.recordingTimer) {
        clearInterval(this.recordingTimer);
      }
      if (this.audioUrl) {
        URL.revokeObjectURL(this.audioUrl);
      }
      document.removeEventListener('click', this.handleClickOutside);
    },

    async handleShowDataDetail(row) {
      console.log(row,'"handleShowDataDetail(scope.row)"')
      this.showDrugDialog = true;
      let res = await getDInfos({id: row.drugId});
      if (this.$refs.kzInfo) {
        this.$refs.kzInfo.setAntcStatus(res.data.antc === 1);
      }
      this.$refs.drugDialog.disablePackingQuantity = res.data.kcId === 1;
      if (this.$refs.basicInfo) {
        this.$refs.basicInfo.disablePackingQuantity = this.$refs.drugDialog.disablePackingQuantity;
      }
      await this.$refs.basicInfo.getDocVtByType();
      if (res.data.list && res.data.list.length > 0) {
        this.$refs.drugDialog.manufacturerData = res.data.list;
      } else if (res.data.manufacturerData) {
        this.$refs.drugDialog.manufacturerData = res.data.manufacturerData;
      }
      this.westSonData = res.data;

      await this.$refs.drugDialog.open({...this.westAddForm, ...res.data}, 'view')
    },

    async batchDeriveExcelSeeDoctorData() {
      await withLoading(this, '数据导出中...')(async () => {
        try {
          // 1. 获取二进制数据（与原有逻辑完全一致)
          const result = await batchDeriveExcelSeeDoctorData({
            startTime: this.seedoctorQueryParams.startTime,
            endTime: this.seedoctorQueryParams.endTime,
          });

          // 2. 创建Blob（保持相同MIME类型）
          const blob = new Blob([result], {
            type: 'application/vnd.ms-excel' // 与您原代码完全一致
          });

          // 3. 优先尝试原生保存对话框
          if ('showSaveFilePicker' in window) {
            const fileHandle = await window.showSaveFilePicker({
              types: [{
                description: 'Excel文件',
                accept: {
                  'application/vnd.ms-excel': ['.xlsx'], // 与原下载相同格式
                  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx']
                }
              }],
              suggestedName: `就诊信息_${new Date().toLocaleDateString('zh-CN')}.xlsx` // 相同文件名规则
            });

            const writable = await fileHandle.createWritable();
            await writable.write(blob);
            await writable.close();

            this.$message.success('文件已保存至选择的位置！');
          }
          // 4. 浏览器不支持时自动降级为原下载逻辑
          else {
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `诊疗数据_${new Date().toLocaleDateString('zh-CN')}.xlsx`; // 相同文件名
            link.click();

            setTimeout(() => {
              URL.revokeObjectURL(url);
            }, 100);
          }

        } catch (error) {
          if (error.name === 'AbortError') return;

          console.error('导出失败:', error);
          if (error.response?.data instanceof Blob) {
            const errorText = await error.response.data.text();
            try {
              const errData = JSON.parse(errorText);
              this.$message.error(errData.message || '导出失败');
            } catch {
              this.$message.error('服务器返回异常数据');
            }
          } else {
            this.$message.error(error.message || '导出失败');
          }
        }
      });
    },

    setRowClassName({row}) {
      if (row.skintstDicm === 1) {
        console.log(row, 'rowrowrowrowrowrowrowrowrowrow')
        if (row.skintstDicmResult === 2) {
          return 'row-positive';
        } else if (row.skintstDicmResult === 1) {
          return 'row-negative';
        }
      }
      return '';
    },

    async getHistoryMedicalData(row) {
      await withLoading(this, '数据加载中...')(async () => {
        const res = await getDoctoradvice({seeDoctorId: row.id});
        if (res.code === 200) {
          this.historyMedicalData = res.data;
          this.historyMedicalDialogVisible = true;
        } else {
          this.$message.error(res.message)
        }
      });
    },

    handleCancelSeedoctorDataList() {
      this.seedoctorQueryParams = Object.assign({}, this.$options.data.call(this).seedoctorQueryParams)
      this.sevenDayDialogVisible = false;
    },

    handleGroupInfusionSync(currentRow) {
      if (currentRow.grpStat == null) return;
      const newSpeed = currentRow.speed;
      // 使用缓存避免重复过滤
      const grpStat = currentRow.grpStat;
      for (let i = 0; i < this.westMedicineTableData.length; i++) {
        const item = this.westMedicineTableData[i];
        if (item.grpStat === grpStat) {
          this.$set(item, 'speed', newSpeed);
        }
      }
    },

    handleCancelAiseForm() {
      this.$refs.aiseFormRef.resetFields();
      this.aiseForm = Object.assign({}, this.$options.data.call(this).aiseForm)
      this.aiseAddOrEditMedicineDialog = false;
    },

    handleKeyPress(event) {
      // 检查是否为 F9 键（兼容 key 和 keyCode）
      if (event.key === 'F9' || event.keyCode === 120) {
        event.preventDefault(); // 阻止默认行为
        this.handleIdCardData(); // 调用你的业务方法
      }
    },

    checkHasDisease(inputString) {
      if (!inputString || typeof inputString !== 'string') {
        return {hasDisease: false, matchedKeywords: []};
      }

      // 缓存疾病列表，避免重复拆分
      if (!this._diseasesArray) {
        this._diseasesArray = this.diseaseList.split('、');
      }

      // 使用Set提高查找效率
      const matchedKeywords = [];
      for (let i = 0; i < this._diseasesArray.length; i++) {
        const disease = this._diseasesArray[i];
        if (inputString.includes(disease)) {
          matchedKeywords.push(disease);
        }
      }

      return {
        hasDisease: matchedKeywords.length > 0,
        matchedKeywords: matchedKeywords
      };
    },

    async checkDiseaseAndConfirm(formData, row) {
      // 快速路径：如果药品没有限制使用标记，直接返回true
      if (row.lmtusedB !== 1) {
        return true;
      }

      // 1. 检查药品名称是否包含禁忌症名称
      const aiseId = this.patientForm.aiseId;
      let aiseName = null;
      let isDrugContraindicated = false;

      if (aiseId) {
        // 使用缓存避免重复查找
        if (!this._aiseNameCache) {
          this._aiseNameCache = {};
        }

        if (this._aiseNameCache[aiseId] === undefined) {
          const aiseItem = this.aiseListOptions.find(item => item.id === aiseId);
          this._aiseNameCache[aiseId] = aiseItem?.label || null;
        }

        aiseName = this._aiseNameCache[aiseId];
        isDrugContraindicated = aiseName && row.drugName.includes(aiseName);
      }

      // 2. 拼接所有病史字段 - 只在需要时执行
      const isPregnantOrMinorWithLimit = (this.patientForm.pregnant || this.patientForm.ageYear <= 14);

      // 如果已经有禁忌症或者是孕妇/未成年人，就不需要检查疾病了
      let diseaseResult = {hasDisease: false, matchedKeywords: []};

      if (!isDrugContraindicated && !isPregnantOrMinorWithLimit) {
        const combinedString = [
          formData.patientTell,
          formData.nowHistory,
          formData.beforeHistory,
          formData.westernDiagnos
        ].filter(Boolean).join(' '); // 过滤掉空值再拼接

        // 3. 检查病史中是否包含慢性病关键词
        diseaseResult = this.checkHasDisease(combinedString);
      }

      const hasDiseaseWithLimit = diseaseResult.hasDisease;

      // 4. 构建风险提示消息 - 只在有风险因素时构建
      const riskFactors = [];

      if (isDrugContraindicated) {
        riskFactors.push(`药品名称包含禁忌症: ${aiseName}`);
      }
      if (hasDiseaseWithLimit) {
        riskFactors.push(`慢性疾病: ${diseaseResult.matchedKeywords.join('、')}`);
      }
      if (isPregnantOrMinorWithLimit) {
        riskFactors.push(`患者为${this.patientForm.pregnant ? '孕妇' : '未成年人'}`);
      }

      // 5. 如果有风险因素，弹出确认框
      if (riskFactors.length > 0) {
        const message = `
      <strong>检测到以下风险因素:</strong><br>
      ${riskFactors.join('<br>')}<br>
      ${row.lmtusedRemark ? `限定备注: ${row.lmtusedRemark}<br>` : ''}
      请确认是否继续操作?
    `;

        try {
          await this.$confirm(
              message,
              '风险提示',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: true
              }
          );
          return true; // 用户确认继续
        } catch {
          return false; // 用户取消操作
        }
      }

      return true; // 无风险，默认继续
    },

    tableRowClassName({row}) {
      if (row.lmtusedB === 1) {
        return 'warning-row';
      }
      return '';
    },

    async handleIdCardData() {
      await withLoading(this, '读取身份证中...')(async () => {
        try {
          if (!this.receptionModalVisible) return;
          if (this.patientForm.certno && this.patientForm.certno.trim() !== '') return;
          const res = await readIdCard();
          this.patientForm.certno = res.cardno;
          this.patientForm.naplAddName = res.address;
          this.patientForm.name = res.name;
          this.patientForm.naty = getNationalityId(this.ntlyOptions, res.nation) ?? 1;
          this.naplPleasett = res.address;
          const isExist = await this.certnoMonitor(this.celerityFilingForm);
          if (isExist === 1) {
            this.patientForm.patId = res.cardno;
            await this.handleSearch();
            this.$message.warning("已自动匹配存在患者信息")
          }
        } catch (error) {
          this.$message.error(error)
        }
      });
    },

    async printOutpatientsDerive() {
      await withLoading(this, '数据导出中...')(async () => {
        try {
          // 1. 获取二进制数据
          const result = await printOutpatientsDerive({
            seeDoctorId: this.patientChooseForm.seeDoctorId
          });

          // 2. 创建Blob
          const blob = new Blob([result], {
            type: 'application/vnd.ms-excel'
          });

          // 3. 提取导出逻辑到复用函数
          await this._saveExcelFile(blob, `诊疗数据_${new Date().toLocaleDateString('zh-CN')}.xlsx`);
        } catch (error) {
          if (error.name === 'AbortError') return; // 用户取消保存不报错

          console.error('导出失败:', error);
          this._handleExportError(error);
        }
      });
    },

    // 提取共用的Excel文件保存逻辑
    async _saveExcelFile(blob, filename) {
      // 优先尝试原生保存对话框
      if ('showSaveFilePicker' in window) {
        try {
          const fileHandle = await window.showSaveFilePicker({
            types: [{
              description: 'Excel文件',
              accept: {
                'application/vnd.ms-excel': ['.xlsx'],
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx']
              }
            }],
            suggestedName: filename
          });

          const writable = await fileHandle.createWritable();
          await writable.write(blob);
          await writable.close();

          this.$message.success('文件已保存至选择的位置！');
        } catch (error) {
          if (error.name !== 'AbortError') {
            // 如果不是用户取消，则降级到传统下载
            this._fallbackDownload(blob, filename);
          }
        }
      } else {
        // 浏览器不支持时使用传统下载
        this._fallbackDownload(blob, filename);
      }
    },

    // 传统下载方法
    _fallbackDownload(blob, filename) {
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename;
      link.click();

      // 及时释放URL对象
      setTimeout(() => URL.revokeObjectURL(url), 100);
    },

    // 处理导出错误
    async _handleExportError(error) {
      if (error.response?.data instanceof Blob) {
        try {
          const errorText = await error.response.data.text();
          const errData = JSON.parse(errorText);
          this.$message.error(errData.message || '导出失败');
        } catch {
          this.$message.error('服务器返回异常数据');
        }
      } else {
        this.$message.error(error.message || '导出失败');
      }
    },

    getPricSummary(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }

        // 只计算 pric 列（注意列名是否正确）
        if (column.property === 'pric') {
          const values = data
              .map(item => {
                const val = item[column.property];
                // 处理可能的 null、undefined 或空字符串
                return val === null || val === undefined || val === '' ? 0 : Number(val);
              })
              .filter(value => !isNaN(value)); // 确保都是有效数字

          const sum = values.reduce((prev, curr) => prev + curr, 0);
          sums[index] = sum.toFixed(2); // 保留2位小数
        } else {
          sums[index] = ''; // 其他列不显示汇总
        }
      });

      return sums;
    },

    handleCancelAddUnit() {
      this.addUnitForm = Object.assign({}, this.$options.data.call(this).addUnitForm)
      this.addUnitModalVisible = false;
    },

    checkSelectable(row, index) {
      // 示例：只允许未删除的行被选中
      return row.orderType !== 5;
    },

    handleSelectionActiveChange(val) {
      this.multipleActiveSelection = val;
      console.log('当前选中：', val);
    },
    // 防抖搜索方法
    debouncedWestSearch() {
      clearTimeout(this.westSearchDebounce);
      this.westSearchDebounce = setTimeout(() => {
        this.handleSearchWestMedicine();
      }, this.searchDebounceTime);
    },

    debouncedChinaSearch() {
      clearTimeout(this.chinaSearchDebounce);
      this.chinaSearchDebounce = setTimeout(() => {
        this.handleSearchChinaMedicine()
      }, this.searchDebounceTime);
    },

    // 分页处理
    handleWestPageChange(page) {
      this.westPagination.currentPage = page
    },

    handleChinaPageChange(page) {
      this.chinaPagination.currentPage = page
    },

    formatPrescriptionContent(content) {
      if (!content) return '';

      // 1. 按括号分割内容（保留括号）
      const items = content.split(/($[^)]+$)/g)
          .filter(item => item.trim());

      // 2. 重新组合为换行字符串
      return items.join('\n');
    },

    async handleOpenDrawer(val) {
      try {
        switch (val) {
          case 'outpatientsDiagnosis':
            await this.previewOutpatientsDiagnosisCombined();
            this.outpatientsDiagnosis = true;
            break;

          case 'medicalRecord':
            await this.previewMedicalRecord();
            this.medicalRecord = true;
            break;
        }
      } catch (error) {
        console.error('打开抽屉出错:', error);
        this.$message.error('加载数据失败，请重试');
      }
    },

    async planWestPrescriptionData() {
      const clinicData = await doccliniclist();
      const clinic = clinicData.data.map(item => {
        return {
          id: item.id, label: item.name
        }
      })
      const formatMedicineGroups = (medicines) => {
        // 分离分组与非分组药品（严格按grpStat判断）
        const groupedMeds = medicines.filter(med => med.grpStat != null);
        const ungroupedMeds = medicines.filter(med => med.grpStat == null);

        // 分组处理（保持原逻辑）
        const groupedResult = groupedMeds.reduce((acc, med) => {
          const groupKey = med.grpStat;
          if (!acc[groupKey]) {
            acc[groupKey] = {
              grpStat: groupKey,
              items: []
            };
          }
          acc[groupKey].items.push({
            name: med.drugName,
            pacSpec: med.pacSpec || "",
            medcWay: this.medicationWayOptions.find(item => item.id === med.medcWayId)?.label,
            usedfrqu: this.medicationFrequencyOptions.find(item => item.id === med.usedfrquId)?.label
          });
          return acc;
        }, {});

        return {
          grouped: Object.values(groupedResult),
          ungrouped: ungroupedMeds.map(med => ({
            name: med.drugName,
            pacSpec: med.pacSpec || "",
            medcWay: this.medicationWayOptions.find(item => item.id === med.medcWayId)?.label,
            usedfrqu: this.medicationFrequencyOptions.find(item => item.id === med.usedfrquId)?.label
          }))
        };
      };

      const generatePrescriptionHtml = (data) => {
        // 分组药品（上下蓝线包裹）
        const groupedHtml = data.grouped.map(group => `
    <div style="
      border-top: 1px solid #1E90FF;
      border-bottom: 1px solid #1E90FF;
      border-left: 2px solid #1E90FF;
      padding: 2px 0 2px 8px;
      margin: 4px 0;
    ">
      ${group.items.map(item => `
        <div style="line-height: 1.5; font-family: '仿宋';">
          ${item.name}(包装规格:${item.pacSpec})(${item.medcWay})(${item.usedfrqu})
        </div>
      `).join('')}
    </div>
  `).join('');

        // 非分组药品（无边框）
        const ungroupedHtml = data.ungrouped.map(item => `
    <div style="margin: 3px 0; padding-left: 5px; line-height: 1.5;">
      ${item.name}(包装规格:${item.pacSpec})(${item.medcWay})(${item.usedfrqu})
    </div>
  `).join('');

        return groupedHtml + ungroupedHtml;
      };


      const medicineData = formatMedicineGroups(this.westMedicineTableData || []);
      const medicineGroupsHtml = generatePrescriptionHtml(medicineData);
      return {
        clinicPrescriptionName: clinic.find(item => item.id === this.userInfo.clinicId)?.label + '处方笺',
        isGrowUp: this.patientForm.ageYear >= 18 ? '成人' : '未成年',
        rxType: this.rxTypeOptions.find(item => item.id === this.addWesternForm.rxType)?.label,
        patId: this.patientForm.patId,
        prhCostType: this.prhCostOption.find(item => item.id === this.patientForm.prhCostType)?.label,
        name: this.patientForm.name,
        sex: this.sexOptions.find(item => item.id === parseInt(this.patientForm.sex))?.label,
        age: this.patientForm.ageYear,
        dept: this.deptOptions.find(item => item.id === this.userInfo.selDept)?.label,
        seedoctorId: this.patientChooseForm.seeDoctorId,
        date: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        address: this.conerPleasett + this.patientForm.conerAddName,
        westernDiagnos: this.addSeedoctorForm.westernDiagnos,
        remake: this.westernMedicineForm.remark,
        doctor: this.userInfo.staffName,
        prescriptionAmount: this.westernMedicineForm.prescriptionAmt,
        phayId: this.westPhayOption[0].label,
        medicineGroups: medicineGroupsHtml
      };
    },

    async planChinaPrescriptionData() {
      const clinicData = await doccliniclist();
      const clinic = clinicData.data.map(item => {
        return {
          id: item.id, label: item.name
        }
      })
      const chinaData = {
        clinicPrescriptionName: clinic.find(item => item.id === this.userInfo.clinicId)?.label + '处方笺',
        isGrowUp: this.patientForm.ageYear >= 18 ? '成人' : '未成年',
        patId: this.patientForm.patId,
        prhCostType: this.prhCostOption.find(item => item.id === this.patientForm.prhCostType)?.label,
        name: this.patientForm.name,
        sex: this.sexOptions.find(item => item.id === parseInt(this.patientForm.sex))?.label,
        age: this.patientForm.ageYear,
        dept: this.deptOptions.find(item => item.id === this.userInfo.selDept)?.label,
        seedoctorId: this.patientChooseForm.seeDoctorId,
        date: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        address: this.conerPleasett + this.patientForm.conerAddName,
        chinaDiagnose: this.addSeedoctorForm.chinaDiagnose,
        westernDiagnos: this.addSeedoctorForm.westernDiagnos,
        doctor: this.userInfo.staffName,
        prescriptionAmount: this.addChinaForm.predictMoney,
        phayId: this.chinaPhayOption[0].label,
      }
      this.addChinaForm.tcmDetailsVOS.forEach((item, index) => {
        const line1 = `${item.drugName}${item.sdoseCnt}g(${item.sdoseCnt * this.addChinaForm.tcmCnt})`;
        const line2 = item.methodName?.trim() ? `(${item.methodName})` : '';

        // 使用HTML格式，调整第二行向左偏移
        chinaData[`chineseMedicine${index + 1}`] =
            `<div style="font-family: monospace; position: relative;">${line1}
             <div style="text-align: center; position: relative; left: -20px;">${line2}</div>
            </div>`;
      });
      return chinaData;
    },

    async printWestPrescription(code) {
      const westPrescriptionData = await this.planWestPrescriptionData();
      console.log(westPrescriptionData, 'westPrescriptionDatawestPrescriptionDatawestPrescriptionData')
      westPrescriptionData.code = code;
      printUtil.init(westPrescription);
      printUtil.print(westPrescriptionData);
    },

    async printChinaPrescription(code) {
      const chinaPrescriptionData = await this.planChinaPrescriptionData();
      chinaPrescriptionData.code = code;
      printUtil.init(chinaPrescription);
      printUtil.print(chinaPrescriptionData);
      await new Promise(resolve => setTimeout(resolve, 1000));
      await Promise.all(
          this.medicalAdviceData.map(item =>
              editDoctoradvice({id: item.id, print: 1})
          )
      );
    },

    async planOutpatientsDiagnosis() {
      const res = await getDiagnosisInfo({seeDoctorId: this.patientChooseForm.seeDoctorId});
      const result = {};
      const allergen = this.aiseListOptions.find(item => item.id === this.patientForm.aiseId)?.label ?? null;
      result.sex = this.sexOptions.find(item => item.id === res.data.sex).label;
      result.ntlyId = this.ntlyOptions.find(item => item.id === res.data.ntlyId)?.label;
      result.naty = this.nationOption.find(item => item.id === res.data.naty)?.label;
      result.professionalTitle = this.profttlOption.find(item => item.id === parseInt(res.data.professionalTitle))?.label;
      result.conerAddName = this.patientForm.conerAddJoinName + this.patientForm.conerAddName;
      result.regTime = res.data.regTime === null ? res.data.seeDoctorTime : res.data.regTime;
      result.phrAlgsDrugAiseId = res.data.phrAlgsDrugAiseId === null ? allergen : res.data.phrAlgsDrugAiseId;
      result.seeDoctorId = this.patientChooseForm.seeDoctorId;
      result.mrgState = this.mrgStateOptions.find(item => item.id === res.data.mrgState)?.label;
      const west = res.data.diagnosisList.filter(item => item.diagnosticCategory === '1'); // 西药
      const china = res.data.diagnosisList.filter(item => item.diagnosticCategory === '2'); // 中药
      west.slice(0, 3).forEach((item, index) => {
        const num = index + 1;
        result[`diagnosticName${num}`] = item.diagnosticName;
        result[`icdCode${num}`] = item.icdCode;
      });
      china.slice(0, 3).forEach((item, index) => {
        const num = index + 4;
        result[`diagnosticName${num}`] = item.diagnosticName;
        result[`icdCode${num}`] = item.icdCode;
      });
      const mergedRes = {...res.data, ...result};
      console.log(mergedRes, 'mergedResmergedResmergedResmergedResmergedResmergedResmergedRes')
      return mergedRes;
    },

    planMedicalRecord() {
      // 1. 处理需要查找的字段
      const department = this.deptOptions.find(item => item.id === this.userInfo.selDept)?.label ?? null;
      const allergen = this.aiseListOptions.find(item => item.id === this.patientForm.aiseId)?.label ?? null;
      const bloodPressure = this.patientForm.syspre && this.patientForm.diapre
          ? `${this.patientForm.syspre}-${this.patientForm.diapre}mmoL`
          : null;
      const therapyOpinion = this.medicalAdviceData
          .filter(item => item.orderType !== 5)
          .map(item => `(${item.content})`);
      if (therapyOpinion.length > 0) {
        therapyOpinion.unshift('');
      }
      console.log(this.patientForm, 'this.patientFormthis.patientFormthis.patientForm')
      return {
        patId: this.patientForm.patId,
        name: this.patientForm.name,
        sex: this.patientForm.sex === '1' ? '男' : '女',
        ageYear: this.patientForm.ageYear,
        seedoctorcType: this.patientForm.repeated === 1 ? '复诊' : '初诊',
        seeDoctorDate: dayjs().format('YYYY-MM-DD'),
        selDept: department,
        syspre: bloodPressure,
        westernDiagnos: this.addSeedoctorForm.westernDiagnos,
        patientTell: this.addSeedoctorForm.patientTell,
        nowHistory: this.addSeedoctorForm.nowHistory,
        beforeHistory: this.addSeedoctorForm.beforeHistory,
        aiseId: allergen,
        conerTel: this.patientForm.conerTel,
        conerAddName: this.patientForm.conerAddJoinName + this.patientForm.conerAddName,
        userId: this.userInfo.staffName,
        currentDate: dayjs().format('YYYY-MM-DD'),
        therapyOpinion: therapyOpinion.join('&nbsp;')
      };
    },

    async printMedicalRecord() {
      try {
        // 1. 先执行打印
        printUtil.init(medicalRecordOutpatient);
        printUtil.print(this.planMedicalRecord());
        await new Promise(resolve => setTimeout(resolve, 1000));
        await Promise.all(
            this.medicalAdviceData.map(item =>
                editDoctoradvice({id: item.id, print: 1})
            )
        );

        await this.resetDisposeAndAdviceData();
      } catch (error) {
        this.$message.error('操作失败');
      }
    },

    async previewMedicalRecord() {
      try {
        // 获取预览内容
        const data = this.planMedicalRecord();

        // 初始化模板
        const template = new hiprint.PrintTemplate({
          template: medicalRecordOutpatient,
        });

        // 获取HTML内容并转换为字符串
        const htmlObj = template.getHtml(data);
        this.medicalRecordHTML = this.extractHtmlString(htmlObj);
      } catch (error) {
        console.error('预览病历文书失败:', error);
        this.$message.error('预览病历文书失败');
      }
    },

    async previewOutpatientsDiagnosisCombined() {
      const res = await this.planOutpatientsDiagnosis()
      // 初始化第一个模板
      const template1 = new hiprint.PrintTemplate({
        template: outpatientsDiagnosis,
      });

      // 获取第一个模板的HTML并转换为字符串

      const htmlObj1 = template1.getHtml(res);
      const html1 = this.extractHtmlString(htmlObj1);

      // 初始化第二个模板
      const template2 = new hiprint.PrintTemplate({
        template: outpatientsDiagnosis2,
      });

      // 获取第二个模板的HTML并转换为字符串
      const htmlObj2 = template2.getHtml(res);
      const html2 = this.extractHtmlString(htmlObj2);

      // 合并两个HTML
      this.outpatientsDiagnosisHTML = `${html1}<hr style="margin: 20px 0; border: 1px dashed #ccc;">${html2}`
    },

    async printOutpatientsDiagnosisCombined() {
      const res = await this.planOutpatientsDiagnosis()
      // 打印第一个模板
      printUtil.init(outpatientsDiagnosis);
      printUtil.print(res);

      // 延迟一会儿（避免浏览器拦截连续打印）
      await new Promise(resolve => setTimeout(resolve, 500));

      // 打印第二个模板
      printUtil.init(outpatientsDiagnosis2);
      printUtil.print(res);
    },

    extractHtmlString(htmlObj) {
      // 如果是jQuery对象
      if (htmlObj && htmlObj.jquery) {
        return htmlObj.html();
      }
      // 如果是DOM元素
      else if (htmlObj && htmlObj.outerHTML) {
        return htmlObj.outerHTML;
      }
      // 如果已经是字符串
      else if (typeof htmlObj === 'string') {
        return htmlObj;
      }
      // 其他情况尝试转换为字符串
      else {
        console.warn('无法识别的HTML对象类型:', htmlObj);
        return String(htmlObj);
      }
    },

    clearWestGroupsCode() {
      // 1. 获取当前选中行
      const selectedRows = this.$refs.westMedicineTableData.selection;

      // 2. 确定清除范围
      const targetRows = selectedRows.length > 0
          ? selectedRows
          : this.westMedicineTableData;

      // 3. 清除所有分组标识
      targetRows.forEach(row => {
        row.grpStat = null;       // 清除分组ID
        row.grpColor = null;      // 清除颜色标识
        row._isFrquDisabled = false; // 恢复用药频率编辑
        row._isMedcWayDisabled = false; // 恢复给药方式编辑
      });

      // 4. 清除DOM上的旗帜标志（关键步骤）
      this.$nextTick(() => {
        const table = this.$refs.westMedicineTableData.$el;
        // 移除所有旗帜元素
        table.querySelectorAll('.group-flag').forEach(flag => flag.remove());
        // 恢复所有用药频率选择器
        table.querySelectorAll('.disabled-frqu').forEach(el => {
          el.classList.remove('disabled-frqu');
          const input = el.querySelector('input');
          if (input) input.disabled = false;
        });

        // 5. 重置表格状态
        this.sortGroupedRows();
        this.$refs.westMedicineTableData.clearSelection();
      });
    },

    async createWestGroupsCode() {

      // 1. 获取当前选中行
      const selectedRows = this.$refs.westMedicineTableData.selection;
      if (selectedRows.length === 0) return;

      // 2. 检查给药频率是否一致
      const firstFrquId = selectedRows[0].usedfrquId;
      const medcWayId = selectedRows[0].medcWayId;
      const isFrquSame = selectedRows.every(row => row.usedfrquId === firstFrquId);
      const medicationFrequency = this.medicationFrequencyOptions.find(item => item.id === firstFrquId)?.label;
      if (!medicationFrequency) {
        this.$message.warning("请选择用药频率再进行分组");
        return;
      }
      if (!isFrquSame) {
        // 使用Element UI弹窗替换原生confirm
        try {
          await this.$confirm(
              `所选药品给药方式不一致（存在${selectedRows.length}种），是否强制分组？\n分组后将统一使用第一种【用药频率】:${medicationFrequency}`,
              '提示',
              {
                confirmButtonText: '强制分组',
                cancelButtonText: '取消',
                type: 'warning'
              }
          );
          // 用户点击确认，继续执行后续代码
        } catch {
          this.$message.warning('已取消分组操作');
          return; // 用户点击取消则终止
        }
      }

      // 4. 生成分组ID和颜色（保持你的原有逻辑）
      const newGroupId = parseInt(String(Date.now()).slice(-5));
      const usedColors = new Set(this.westMedicineTableData.filter(item => item.grpColor).map(item => item.grpColor));
      const newColor = this.color.find(c => !usedColors.has(c)) || this.color[0];

      // 5. 更新选中行数据（统一给药频率）
      selectedRows.forEach((row, index) => {
        row.grpStat = newGroupId;
        row.grpColor = newColor;
        row._isFrquDisabled = index > 0; // 第一条不禁用，其他行禁用
        row._isMedcWayDisabled = index > 0; // 第一条不禁用，其他行禁用
        row.usedfrquId = index > 0 ? firstFrquId : row.usedfrquId;
        row.medcWayId = index > 0 ? medcWayId : row.medcWayId;
        this.getWestSdoseSum(row)
      });

      // 6. 排序和渲染（保持你的原有逻辑）
      this.sortGroupedRows();
      this.$nextTick(() => {

        this.renderGroupFlags();
        this.$refs.westMedicineTableData.clearSelection();
      });
    },

    sortGroupedRows() {
      this.westMedicineTableData.sort((a, b) => {
        if (a.grpStat && !b.grpStat) return -1;  // 有分组的排前面
        if (!a.grpStat && b.grpStat) return 1;
        if (a.grpStat === b.grpStat) return 0;  // 相同分组保持原序
        return (a.grpStat || 0) - (b.grpStat || 0); // 不同分组按ID排序
      });
    },

    renderGroupFlags() {
      const table = this.$refs.westMedicineTableData.$el;

      // 1. 清除所有旧旗帜和禁用状态
      table.querySelectorAll('.group-flag, .disabled-frqu').forEach(el => el.remove());

      // 2. 颜色生成器（不同grpStat分配不同颜色）
      const colorMap = {}; // 记录每个grpStat对应的颜色
      const colorPalette = [
        '#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A',
        '#98D8C8', '#F06292', '#7986CB', '#9575CD'
      ];
      let colorIndex = 0;

      // 3. 统计分组信息 {grpStat: [行索引]}
      const groupMap = {};
      this.westMedicineTableData.forEach((item, index) => {
        if (item.grpStat) {
          if (!groupMap[item.grpStat]) {
            groupMap[item.grpStat] = [];
            // 为新的grpStat分配颜色（循环使用调色板）
            colorMap[item.grpStat] = colorPalette[colorIndex % colorPalette.length];
            colorIndex++;
          }
          groupMap[item.grpStat].push(index);
        }
      });

      // 4. 处理每个分组
      Object.entries(groupMap).forEach(([grpStat, rowIndexes]) => {
        if (rowIndexes.length <= 1) return; // 忽略孤立分组

        const groupColor = colorMap[grpStat]; // 获取该分组的颜色

        // 4.1 添加旗帜（所有分组行使用相同颜色）
        rowIndexes.forEach(index => {
          const row = table.querySelectorAll('.el-table__row')[index];
          if (!row) return;

          const firstCell = row.querySelector('.el-table__cell:first-child');
          if (!firstCell) return;

          const flag = document.createElement('div');
          flag.className = 'group-flag';
          flag.innerHTML = `
        <svg width="16" height="16" viewBox="0 0 24 24">
          <path fill="${groupColor}" d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z"/>
        </svg>
      `;
          firstCell.appendChild(flag);
        });

        // 4.2 禁用非首行的用药频率选择器（保持不变）
        rowIndexes.slice(1).forEach(index => {
          const row = table.querySelectorAll('.el-table__row')[index];
          if (!row) return;

          const select = row.querySelector('.usedfrquId-cell .el-select');
          if (select) {
            select.classList.add('disabled-frqu');
            select.querySelector('input').disabled = true;
            select.style.opacity = '0.6';
            select.style.cursor = 'not-allowed';
          }
        });
      });
    },

    handleWestGroups(selectedRows) {
      this.westGroupsTableData = selectedRows;
    },

    async handleAddReception(row) {
      await withLoading(this, '数据加载中...')(async () => {
        this.patientForm = Object.assign({}, this.$options.data.call(this).patientForm)
        this.patientForm.patId = row.cardid;
        await this.handleSearch();
        await this.getRegisterType();
        const mainRegType = this.registerOptions.find(item => item.mainType = 1);
        if (this.registerOptions.length < 1) return this.$message.warning("请去添加挂号类别")
        this.receptionForm.regTypeId = mainRegType.id;
        this.receptionForm.price = mainRegType.odcost;
        await this._handleAddFastReception({skipValidation: true});
        this.sevenDayDialogVisible = false;
        this.historyMedicalDialogVisible = false;
      });
    },

    async handleQuote(row) {
      row.status = '1';
      row.doctorId = this.userInfo.staffId;
      await editReception(row);
      this.loadData();
      await this.handleClickReceptionRow(row, 1);
      this.sevenDayDialogVisible = false;
      this.historyMedicalDialogVisible = false;
    },

    handleCloseChoosePatient() {
      this.patientDialogVisible = false;
    },

    async loadAndDisplayAddress(type = 'coner') {
      try {
        // 1. 确保省级数据已加载
        if (this.provinces.length === 0) {
          await this.loadProvincial();
        }

        // 2. 根据地址类型获取对应数据
        const codeKey = `${type}AddCodeArr`;
        const nameKey = `${type}AddName`;
        const codes = this.patientForm[codeKey] || [];

        let currentNodes = this.provinces;
        const loadedCodes = [];
        const addressNames = [];
        const levelConditions = ['area_p_code', 'area_p_code', 'area_c_code', 'area_d_code', 'area_t_code'];

        // 3. 按层级逐级加载
        for (let i = 0; i < codes.length; i++) {
          const code = codes[i];
          const level = i + 1; // 1:省, 2:市, 3:县, 4:镇, 5:乡

          // 尝试从当前层级查找节点
          let targetNode = currentNodes.find(node => node.areaCode === code);

          // 如果未找到，尝试动态加载该级数据
          if (!targetNode) {
            const parentCode = i > 0 ? codes[i - 1] : undefined;
            const params = {
              areaCode: parentCode,
              areaLevel: level,
              condtion: levelConditions[i]
            };

            const res = await getArea(params);
            currentNodes = res.data || [];
            targetNode = currentNodes.find(node => node.areaCode === code);

            // 如果是省级数据，更新this.provinces
            if (level === 1) {
              this.provinces = currentNodes;
            }
          }

          if (!targetNode) {
            break;
          }

          loadedCodes.push(code);
          addressNames.push(targetNode.areaName);
          // 动态加载子级数据（如果未到末级）
          if (!targetNode.leaf && level < 5) {
            const res = await getArea({
              areaCode: code,
              areaLevel: level + 1,
              condtion: levelConditions[level]
            });
            targetNode.children = res.data || [];
            currentNodes = targetNode.children;
          }
        }
        if (type === 'coner') {
          this.patientForm.conerAddJoinName = addressNames.join('');
        }
        this.$nextTick(() => {
          // 先强制清空以触发响应式更新
          this.patientForm[codeKey] = [];

          // 立即重新赋值（不再使用setTimeout）
          this.$nextTick(() => {
            this.patientForm[codeKey] = [...loadedCodes];
            console.log(this.patientForm, 'this.patientFormthis.patientFormthis.patientForm')
            // 调用内部方法强制更新显示文本
            if (type === "coner") {
              this.conerPleasett = addressNames.join('/');
            } else {
              this.naplPleasett = addressNames.join('/');
            }
            this.addressKey = Date.now(); // 通过key强制刷新组件
          });
        });
      } catch (error) {
        console.error(`加载${type}地址数据失败:`, error);
        this.$message.error('地址加载失败，请重试');
      }
    },

    async loadProvincial() {
      try {
        const res = await getArea({areaLevel: 1, condtion: 'area_p_code'});
        this.provinces = res.data.map(item => ({
          areaCode: item.areaCode,
          areaName: item.areaName,
          areaLevel: 1,
          leaf: false,
        }));
      } catch (error) {
        console.error('加载省级数据失败:', error);
      }
    },

    async loadSelectedPath(type = 'coner') {
      try {
        // 1. 确保省级数据已加载
        if (this.provinces.length === 0) {
          await this.loadProvincial();
        }

        // 2. 根据类型获取对应字段
        const codeKey = `${type}AddCodeArr`;
        const codes = this.patientForm[codeKey] || [];

        // 3. 定义各级请求条件
        const levelConditions = ['area_p_code', 'area_p_code', 'area_c_code', 'area_d_code', 'area_t_code'];
        let currentNodes = this.provinces;
        const loadedCodes = [];

        // 4. 按层级逐级加载
        for (let i = 0; i < codes.length; i++) {
          const code = codes[i];
          const level = i + 1; // 1:省, 2:市, 3:区, 4:镇, 5:社区

          // 尝试从当前层级查找节点
          let targetNode = currentNodes.find(node => node.areaCode === code);

          // 如果未找到，动态加载该级数据
          if (!targetNode) {
            const parentCode = i > 0 ? codes[i - 1] : undefined;
            const params = {
              areaCode: parentCode,
              areaLevel: level,
              condtion: levelConditions[i]
            };
            const res = await getArea(params);
            currentNodes = res.data || [];
            targetNode = currentNodes.find(node => node.areaCode === code);

            // 更新省级数据缓存
            if (level === 1) {
              this.provinces = currentNodes;
            }
          }

          if (!targetNode) {
            break;
          }

          loadedCodes.push(code);

          // 动态加载下一级数据（如果未到末级）
          if (level < 5 && (!targetNode.children || targetNode.children.length === 0)) {
            const nextLevelParams = {
              areaCode: code,
              areaLevel: level + 1,
              condtion: levelConditions[level]
            };
            const res = await getArea(nextLevelParams);
            targetNode.children = res.data || [];

            // 如果是第四级，设置其子节点为叶子节点
            if (level === 5) {
              targetNode.children.forEach(item => {
                item.isLeaf = true;  // 标记为叶子节点，不显示下拉箭头
              });
            }
          }

          currentNodes = targetNode.children || [];
        }

        this.$nextTick(() => {
          // 强制刷新级联选择器
          this.patientForm[codeKey] = [];
          setTimeout(() => {
            this.patientForm[codeKey] = [...loadedCodes];
          }, 200);
        });

      } catch (error) {
        console.error(`加载${type}地址路径失败:`, error);
        this.$message.error(`${type === 'coner' ? '联系' : '籍贯'}地址加载失败，请重试`);
      }
    },

    async initAddressData() {
      try {
        // 确保省级数据已加载
        if (this.provinces.length === 0) {
          await this.loadProvincial();
        }

        // 确保naplAddCodeArr不是null
        this.patientForm.naplAddCodeArr = this.patientForm.naplAddCodeArr || [];

        // 如果存在有效编码才加载路径
        if (this.patientForm.naplAddCodeArr.length > 0) {
          await this.loadSelectedPath('napl');
        }
      } catch (error) {
        console.error('地址初始化失败:', error);
      }
    },

    filterChinaMedicationWay() {
      this.chinaMedicationWayOptions = this.medicationWayOptions.filter(
          item => item.lmtSpc === 2
      );
    },

    async handleThrNotChange() {
      if (this.patientForm.thrNot === 0) {
        this.patientForm.name = '';
        return;
      }
      const today = dayjs().format('YYYYMMDD');
      // 生成4个随机大写字母
      const randomChars = Array.from({length: 5}, () =>
          String.fromCharCode(65 + Math.floor(Math.random() * 26))
      ).join('');

      this.patientForm.name = `三无人员${today}_${randomChars}`;
    },

    handleExecutionPL() {
      this.searchForm = Object.assign({}, this.$options.data.call(this).searchForm);

      this.selExecutionPLDialogVisible = false;
    },

    computeFrequencyNum(val) {
      const frequency = JSON.parse(JSON.stringify(
          this.medicationFrequencyOptions.find(item => item.id === this.searchForm.usedfrquId)
      ));

      if (!frequency || frequency.frquCnt === 0) return; // 避免除零错误

      if (!frequency || frequency.frquPrd <= 0) return; // 避免无效值

      // 计算 executionDays
      if (frequency.frquPrd > frequency.frquCnt) {
        const day = Math.ceil(Math.ceil(val / frequency.frquCnt) * frequency.frquPrd);
        this.$set(this.searchForm, 'executionDays', day);
      } else {
        this.$set(this.searchForm, 'executionDays', Math.ceil(val / frequency.frquCnt));
      }
    },

    computeFrequencyDay(val) {
      const frequency = JSON.parse(JSON.stringify(this.medicationFrequencyOptions.find(item => item.id === this.searchForm.usedfrquId)));
      this.$set(this.searchForm, 'executionNum', frequency.frquCnt * val);
    },

    computeFrequency() {
      const frequency = JSON.parse(JSON.stringify(this.medicationFrequencyOptions.find(item => item.id === this.searchForm.usedfrquId)));
      console.log(frequency, 'frequencyfrequencyfrequencyfrequency')
      this.$set(this.searchForm, 'executionDays', frequency.frquPrd);
      this.$set(this.searchForm, 'executionNum', frequency.frquCnt);
    },

    validateDose() {
      if (this.editDoseValue <= 0) {
        this.$message.warning('用量必须大于0');
        this.editDoseValue = 1; // 重置为最小值
      }
    },

    async resetDisposeAndAdviceData() {
      const res = await getDoctoradvice({seeDoctorId: this.patientChooseForm.seeDoctorId});
      const res2 = await getDoctordispose({seeDoctorId: this.patientChooseForm.seeDoctorId});
      this.doctordisposeTableData = res2.data.map(item => ({
        ...item,
        odcost: item.executionPrice,
        executeOdcost: item.executionAmount,
        doctorName: item.staffId,
        deptName: item.executDeptId,
        count: item.num
      }));
      this.$set(this, 'medicalAdviceData', [...res.data]);
    },

    async resetWestMedicineData() {
      this.westMedicineTableData = [];
      const [res2, res5] = await Promise.all([
        getReceptionDiagnosis({category: 1, seeDoctorId: this.patientChooseForm.seeDoctorId}),
        getDoctoradvice({seeDoctorId: this.patientChooseForm.seeDoctorId}),
      ]);
      this.medicalAdviceData = res5.data;
      this.addSeedoctorForm = {
        ...this.addSeedoctorForm,
        westernDiagnos: res2.map(item => `(${item.diagnosticName})`).join('') || '',
        doctordisposePrescription: res5.data.filter(item => item.orderType === 4).map(item => `${item.content}`).join('') || '',
      };
      this.medicalAdviceData = res5.data.map(item => {
        // 处理 orderType === 0 的数据
        if (item.orderType === 0) {
          let processedContent = item.content
              .replace(/\/n/g, '\n')  // 统一换行符格式
              .split('\n')
              .map(line => line.trim()) // 去除首尾空格
              .filter(line => line.length > 0) // 过滤空行
              .map(line => line.startsWith('(') && line.endsWith(')') ? line : `(${line})`) // 智能加括号
              .join('\n');
          return {
            ...item,
            content: processedContent
          };
        }
        if (item.skintstDicm === 1) {
          if (item.skintstDicmResult === 2) {
            item.content += '\n（皮试结果:阳性）';
          } else if (item.skintstDicmResult === 1) {
            item.content += '\n（皮试结果:阴性）';
          } else if (item.skintstDicmResult === 0) {
            item.content += '\n（皮试结果:未知）';
          }
        }
        // 其他 orderType 的数据原样返回
        return item;
      });
      this.selWestMedicineDialog = false;
      this.addWesternForm = Object.assign({}, this.$options.data.call(this).addWesternForm)
      this.westernMedicineForm = Object.assign({}, this.$options.data.call(this).westernMedicineForm)
    },

    async batchDelOneAdvice() {
      if (this.multipleActiveSelection.length < 1) return this.$message.warning("请勾选数据后再进行操作")
      this.multipleActiveSelection.forEach(item => {
        this.delOneAdvice({id: item.id})
      })
    },

    async delOneAdvice(row) {
      try {
        const res = await delOneAdvice({id: row.id});
        if (res.code === 200) {
          const res2 = await getDoctoradvice({seeDoctorId: this.patientChooseForm.seeDoctorId});
          this.medicalAdviceData = res2.data;
          await this.resetWestMedicineData();
          await this.resetDisposeAndAdviceData();
        } else {
          this.$message.warning(res.message)
        }
      } catch (error) {
        this.$message.error("系统异常:请联系管理员")
      } finally {

      }

    },

    handleCancelSkinTest() {
      this.$refs.skinTestForm.clearValidate();
      this.isSkinTestDoseDialog = false;
      this.westernMedicineSearchQuery = Object.assign(
          {},
          this.$options.data.call(this).westernMedicineSearchQuery
      );
    },

    handleConfirmSkinTest() {
      this.$refs.skinTestForm.validate((valid) => {
        if (valid) {
          // 表单验证通过，执行原有逻辑
          const index = this.westMedicineTableData.findIndex(
              item => item.drugId === this.westernMedicineSearchQuery.id
          );
          if (index !== -1) {
            this.$set(
                this.westMedicineTableData[index],
                'skintstDicm',
                this.westernMedicineSearchQuery.isSkinTest
            );
          }
          // 重置表单数据
          this.westernMedicineSearchQuery = Object.assign(
              {},
              this.$options.data.call(this).westernMedicineSearchQuery
          );
          this.isSkinTestDoseDialog = false;
        } else {
          // 验证失败，不执行任何操作
          return false;
        }
      });
    },

    isTransfusion(id, row) {
      const res = this.medicationWayOptions.find(item => item.id === id);
      if (!res) return;
      row.medcWayType = res.type === 2;
      if (res.type !== 2) {
        this.$set(row, 'speed', '');
      }
      if (row.grpStat != null) {
        this.westMedicineTableData.forEach(item => {
          if (item.grpStat === row.grpStat) {
            this.$set(item, 'medcWayId', id);
            this.$set(item, 'medcWayType', res.type === 2);
            if (res.type !== 2) {
              this.$set(item, 'speed', '');
            }
          }
        });
      }
    },

    handleAddChinaMakeMethod() {
      const index = this.chinaMedicineTableData.findIndex(item =>
          item.drugId === this.checkedchinaPrescriptionId
      )

      console.log(index, 'indexindexindexindex')
      if (index !== -1) {
        this.$set(this.chinaMedicineTableData, index, {
          ...this.chinaMedicineTableData[index],
          methodId: this.checkedchinaMakeMethod.id,
          methodName: this.checkedchinaMakeMethod.label
        })
      }
      this.creationMethodDialogVisible = false;
    },

    handleCheckedChinaMakeMethod(row, index) {
      this.active = index;
      this.checkedchinaMakeMethod = row;
    },

    handleMedicineContextMenu(row, column, event) {
      if (this.isShowPrescription) return;
      event.preventDefault();
      this.showChinaReception = true;
      this.contextMenuLeft = event.clientX;
      this.contextMenuTop = event.clientY;
      this.chinaReceptionRowData = row;
      document.addEventListener('click', this.closeMedicineMenu);
    },

    closeMedicineMenu() {
      this.showChinaReception = false;
      document.removeEventListener('click', this.closeMedicineMenu);
    },

    handleMethodNote(row, e) {
      console.log(row, e, 'handleMethodNotehandleMethodNote')
      this.creationMethodDialogVisible = true;
      this.checkedchinaPrescriptionId = row.drugId;
    },

    handleClearMethod(row, e) {
      delete row.methodId;
      delete row.methodName;
    },

    openDoseDialog(row, index) {
      this.currentEditIndex = index;
      this.editDoseValue = row.sdoseCnt;
      this.showDoseDialog = true;
    },

    confirmEditDose() {
      if (this.currentEditIndex >= 0) {
        this.chinaMedicineTableData[this.currentEditIndex].sdoseCnt = this.editDoseValue;
        this.showDoseDialog = false;
      }
      this.getChinaDosageSum();
    },

    handleClose(done) {
      done();
    },

    handleModifyDosage(row) {
      const findIndex = this.chinaMedicineTableData.findIndex(item => item.drugId === row.drugId)
      this.openDoseDialog(row, findIndex);
    },

    handleDeleteMedicine(row, e) {
      const index = this.chinaMedicineTableData.findIndex(item => item.drugId === row.drugId);
      if (index !== -1) {
        // 创建新数组赋值
        this.chinaMedicineTableData = [
          ...this.chinaMedicineTableData.slice(0, index),
          ...this.chinaMedicineTableData.slice(index + 1)
        ];
        this.getChinaDosageSum();
      }
    },

    handleNumericInput() {
      let value = this.addChinaForm.sdoseCnt;
      value = value
          .replace(/[^\d.]/g, '')           // 移除非数字和小数点
          .replace(/^\./g, '')              // 不能以小数点开头
          .replace(/\.+/g, (match, offset) => offset === 0 ? '.' : ''); // 只保留第一个小数点
      if (value.includes('.')) {
        const parts = value.split('.');
        value = parts[0] + '.' + parts[1].slice(0, 2);
      }
      if (value && parseFloat(value) <= 0) {
        value = '';
        this.$message.warning("请规范填写用量!!!")
      }
      this.addChinaForm.sdoseCnt = value;
    },

    handleDosageEnter() {
      if (!this.addChinaForm.sdoseCnt) return this.$message.warning("请输入剂量!")
      const isExist = this.chinaMedicineTableData.some(
          item => item.drugId === this.chinaChekeCurrentData.drugId
      );
      if (isExist) {
        this.$message.error(`药品【${this.chinaChekeCurrentData.drugName}】已存在处方中!`);
        return;
      }
      this.chinaChekeCurrentData.medicineType = 2;
      const newItem = JSON.parse(JSON.stringify(this.chinaChekeCurrentData));
      newItem.sdoseCnt = parseInt(this.addChinaForm.sdoseCnt);
      this.chinaMedicineTableData.push(newItem)
      this.$set(this.addChinaForm, 'sdoseCnt', '');
      this.chinaMedicineSearchQuery = '';
      this.getChinaDosageSum();
    },

    handleConfirmed(row, newValue) {
      if (!row.hasOwnProperty('originalName')) {
        this.$set(row, 'originalName', row.name.replace('?', ''))
      }

      // 2. 根据复选框状态处理名称
      if (newValue === 1) {
        // 勾选状态:移除问号
        this.$set(row, 'name', row.originalName)
      } else {
        // 取消勾选:添加问号
        this.$set(row, 'name', row.originalName + '?')
      }
    },

    getChinaDosageSum() {
      // 计算总药量（保留2位小数）
      this.addChinaForm.chinaMedicineSum = parseFloat(
          (this.chinaMedicineTableData.reduce(
              (sum, item) => sum + (Number(item.sdoseCnt) || 0),
              0
          ) * (Number(this.addChinaForm.tcmCnt) || 1)).toFixed(2)
      );

      this.addChinaForm.predictMoney = parseFloat(
          (this.chinaMedicineTableData.reduce(
              (sum, item) => sum + ((Number(item.sdoseCnt) || 0) * (Number(item.minSalePric) || 0)),
              0
          ) * (Number(this.addChinaForm.tcmCnt) || 1)).toFixed(2)
      );

      const tcmCnt = Math.max(1, Number(this.addChinaForm.tcmCnt) || 1);
      this.chinaMedicineTableData.forEach(item => {
        item.sdoseSum = parseFloat(
            ((Number(item.sdoseCnt) || 0) * tcmCnt).toFixed(2)
        );
      });

    },

    getWestSdoseSum(row) {
      const sdoseCnt = parseFloat(row.sdoseCnt);
      const prdDays = parseFloat(row.prdDays);
      const prdCnt = parseFloat(row.prdCnt);
      const usedfrquData = this.medicationFrequencyOptions.find(item => item.id === row.usedfrquId);
      if (!usedfrquData) {
        this.$message.error('请选择用药频率！');
        return;
      }

      const unitDose = parseFloat(row.unitDose);

      if (row.sdoseSum === undefined || row.sdoseSum === null || isNaN(row.sdoseSum)) {
        this.$set(row, 'sdoseSum', '待计算');
      }

      if (isNaN(sdoseCnt) || isNaN(prdDays) || isNaN(unitDose)) {
        this.$set(row, 'sdoseSum', '待计算');
        this.$set(this.westernMedicineForm, 'prescriptionAmt', '待计算');
        return;
      }

      // 检查是否 > 0
      if (sdoseCnt <= 0 || prdDays <= 0 || unitDose <= 0) {
        this.$message.warning("单次剂量、周期次数、周期天数必须大于 0！");
        this.$set(row, 'sdoseSum', '待计算');
        this.$set(this.westernMedicineForm, 'prescriptionAmt', '待计算');
        return;
      }

      // 最小单位-单次取整（saleUnt=1且roundUnt=1）
      if (row.saleUnt === 1 && row.roundUnt === 1) {
        // 计算总数量：总用药量/单位剂量，向上取整
        const cnt = Math.ceil(sdoseCnt / row.unitDose) * prdDays * usedfrquData.frquCnt;
        // 设置行数据（统一使用parseFloat保证数字类型）
        this.$set(row, 'sdoseSum', parseFloat((sdoseCnt * usedfrquData.frquCnt * prdDays).toFixed(2)));
        this.$set(row, 'cnt', cnt);
        this.$set(row, 'amount', parseFloat((cnt * row.minSalePric).toFixed(2)));
      }

      // 最小单位-处方取整（saleUnt=1且roundUnt=2/3）
      else if (row.saleUnt === 1 && (row.roundUnt === 2 || row.roundUnt === 3)) {
        // 计算总数量：单次剂量/单位剂量取整后×总次数
        const cnt = Math.ceil(sdoseCnt / row.unitDose) * usedfrquData.frquCnt * prdDays;

        // 设置行数据
        this.$set(row, 'sdoseSum', parseFloat((row.unitDose * cnt).toFixed(2)));
        this.$set(row, 'cnt', cnt);
        this.$set(row, 'amount', parseFloat((cnt * row.minSalePric).toFixed(2)));
      }

      // 包装单位-处方取整（saleUnt=2且roundUnt=2/3）
      else if (row.saleUnt === 2 && (row.roundUnt === 2 || row.roundUnt === 3)) {
        // 包装单位总剂量 = 包装数量×单位剂量
        const pacUnitDose = row.pacCnt * parseFloat(row.unitDose);

        // 计算总数量：总用药量/包装单位剂量，向上取整
        const cnt = Math.ceil((usedfrquData.frquCnt * sdoseCnt * prdDays) / pacUnitDose);
        console.log(pacUnitDose, cnt, 'cntcntcntcntcntcnt')
        // 设置行数据
        this.$set(row, 'sdoseSum', parseFloat((sdoseCnt * usedfrquData.frquCnt * prdDays).toFixed(2)));
        this.$set(row, 'cnt', cnt);
        this.$set(row, 'amount', parseFloat((cnt * row.maxSalePric).toFixed(2)));
      }

      // 包装单位-单次取整（saleUnt=2且roundUnt=1）
      else if (row.saleUnt === 2 && row.roundUnt === 1) {
        // 计算总数量：直接天数乘以周期次数就是整个的包装数量
        const cnt = Math.ceil((usedfrquData.frquCnt * sdoseCnt * prdDays) / row.pacCnt);
        // 设置行数据
        this.$set(row, 'sdoseSum', parseFloat((usedfrquData.frquCnt * sdoseCnt * prdDays).toFixed(2)));
        this.$set(row, 'cnt', cnt);
        this.$set(row, 'amount', parseFloat((cnt * row.maxSalePric).toFixed(2)));
      }

      /*if (row.saleUnt === 2 && (row.roundUnt === 2 ||row.roundUnt === 3)){
        const cnt = Math.ceil((usedfrquData.frquCnt * sdoseCnt * prdDays) / (row.pacCnt * parseInt(row.unitDose)));
        const sdoseSum = (sdoseCnt * usedfrquData.frquCnt * prdDays).toFixed(2);
        this.$set(row, 'sdoseSum', parseFloat(sdoseSum));
        this.$set(row, 'cnt', cnt);
        this.$set(row, 'amount', parseFloat((cnt * row.maxSalePric).toFixed(2)));
      }*/

      /*if (row.saleUnt === 2) {
        if (row.roundUnt === 2 || row.roundUnt === 3){
          const cnt = Math.ceil((usedfrquData.frquCnt * sdoseCnt * prdDays) / (row.pacCnt * parseInt(row.unitDose)));
          const sdoseSum = (sdoseCnt * usedfrquData.frquCnt * prdDays).toFixed(2);
          this.$set(row, 'sdoseSum', parseFloat(sdoseSum));
          this.$set(row, 'cnt', cnt);
          this.$set(row, 'amount', parseFloat((cnt * row.maxSalePric).toFixed(2)));
        } else {
          const cnt = Math.ceil((usedfrquData.frquCnt * sdoseCnt * prdDays) / (row.pacCnt * parseInt(row.unitDose)));
          const sdoseSum = (sdoseCnt * usedfrquData.frquCnt * prdDays).toFixed(2);
          this.$set(row, 'sdoseSum', parseFloat(sdoseSum));
          this.$set(row, 'cnt', cnt);
          this.$set(row, 'amount', parseFloat((cnt * row.maxSalePric).toFixed(2)));
        }
      }*/
      row.prdCnt = row.prdDays * usedfrquData.frquCnt;

// 计算总金额（保留两位小数）
      this.westernMedicineForm.prescriptionAmt = parseFloat(
          this.westMedicineTableData
              .reduce((sum, item) => sum + (item.amount || 0), 0)
              .toFixed(2)
      );
    },

    async selectDrugDosageForm() {
      if (this.drugDosageOption.length > 0) return;
      const res = await selectDrugDosageForm();
      this.drugDosageOption = res.data.map(item => {
        return {
          id: item.id, label: item.dosageName
        }
      })
    },

    async getDosaUnt() {
      if (this.dosaUntOptions.length > 0) return;
      const res = await getDosaUnt();
      this.dosaUntOptions = res.data.map(item => {
        return {
          id: item.id, label: item.name
        }
      })
    },

    async getDrugUnt() {
      if (this.drugUntOptions.length > 0) return;
      const res = await getDrugUnt();
      this.drugUntOptions = res.data.map(item => {
        return {
          id: item.id, label: item.name
        }
      })
      console.log(this.drugUntOptions, 'this.drugUntOptionsthis.drugUntOptions')
      console.log(res, 'resresresresresresresresres')
    },

    async getMedicationFrequency() {
      if (this.medicationFrequencyOptions.length > 0) return;
      const res = await getMedicationWay();
      this.medicationFrequencyOptions = res.data.map(item => {
        return {
          id: item.id, label: item.name, frquCnt: item.frquCnt, frquPrd: item.frquPrd
        }
      })
    },

    async handleSearchChinaMedicine() {
      if (!this.preVerificationUserInfo()) return
      const keyword = this.chinaMedicineSearchQuery.trim()
      /*if (!keyword) {
        this.queryChinaMedicineData = []
        this.searchTriggered = false
        return
      }*/
      this.searchTriggered = true
      try {
        const res = await getChinaDugdpurctable();
        this.queryChinaMedicineData = res.data;
        this.chinaPagination.total = this.queryChinaMedicineData.length;
        this.chinaPagination.currentPage = 1;
      } catch (error) {
        console.error('搜索失败:', error)
        this.queryChinaMedicineData = []
      }
    },

    async handleSearchWestMedicine() {
      if (!this.preVerificationUserInfo()) return
      // 每次调用都清空搜索条件（相当于强制刷新）
      /*this.westMedicineSearchQuery = '';*/
      this.searchTriggered = true;
      try {
        /*const res = await getWestDugdpurctable({
          condition: this.westMedicineSearchQuery,
          dmCode:this.addWesternForm.rxType
        }); */
        /*const res = await getWestDugdpurctable({
          condition: this.westMedicineSearchQuery,
          rxType:this.addWesternForm.rxType
        });*/

        const res = await getWestDugdpurctable();

        this.queryWestMedicineData = (res.data?.map(item => ({
          ...item,
          tableId: item.id,
          expyDate: item.expyDate ? new Date(item.expyDate).toLocaleString().replace(/\//g, '-') : null,
          manuDate: item.manuDate ? new Date(item.manuDate).toLocaleString().replace(/\//g, '-') : null
        }))?.map(({id, ...rest}) => rest) || [])

        this.westPagination.total = this.queryWestMedicineData.length;
        this.westPagination.currentPage = 1;

      } catch (error) {
        console.error('搜索失败:', error);
        this.queryWestMedicineData = [];
        this.westPagination.total = 0;
      } finally {
      }
    },

    async handleSelWestTableRowClick(row) {
      if (row.antcLv !== null && this.userPermission.antibioticAuthorization < row.antcLv) {
        this.$message.warning("员工抗生素权限不足");
        return;
      }

      const permissionMap = {
        2: {field: 'anesthesiaAuthorization', message: "员工麻药类药物权限不足", valid: val => parseInt(val) === 1},
        3: {field: 'poisonPermission', message: "员工毒麻类药物权限不足", valid: val => parseInt(val) === 1},
        4: {field: 'spiritPermission', message: "员工精神I类药物权限不足", valid: val => parseInt(val) === 1},
        5: {
          field: 'spiritPermission',
          message: "员工精神II类药物权限不足",
          valid: val => parseInt(val) === 1 || parseInt(val) === 2
        },
      };
      const aiseName = this.aiseListOptions.find(item => item.id === this.patientForm.aiseId)?.label;
      if (aiseName !== '' && row.drugName.includes(aiseName)) {
        console.log("drugName 包含 aiseName 的文字");
      } else {
        console.log("不包含");
      }
      const permissionCheck = permissionMap[row.dmCode];
      if (permissionCheck && !permissionCheck.valid(this.userPermission[permissionCheck.field])) {
        this.$message.warning(permissionCheck.message);
        return;
      }

      const shouldContinue = await this.checkDiseaseAndConfirm(this.addSeedoctorForm, row);
      if (!shouldContinue) return;

      if (row.skintstDicm === 1) {
        this.isSkinTestDoseDialog = true;
        this.westernMedicineSearchQuery = JSON.parse(JSON.stringify({id: row.drugId, drugName: row.drugName}));
      } else {
        row.skintstDicm = 0;
      }
      row.roundUnt = parseInt(row.roundUnt);
      row.prdDays = 1;
      row.prdCnt = 1;
      row.sdoseCnt = row.minDose;
      row.purcType = parseInt(row.purcType);
      row.rxType = this.addWesternForm.rxType;
      row.unt = row.dosUnt;
      row.medicineType = 1;
      console.log(row, 'rowrowrowrowrowrowrow')
      /*      row.saleUnt =  row.saleUnt === 1 ? saleName+`(${row.minUnt})` : saleName+`(${row.pacUnt})`*/
      row.saleUntName = row.saleUnt === 1 ? row.minUnt : row.pacUnt;
      row.medcWayType = row.medcWayId != null
          ? this.medicationWayOptions.find(item => item.id === row.medcWayId)?.type === 2
          : row.medcWayType;
      this.westMedicineSearchQuery = row.drugName;
      this.westMedicineTableData.push(JSON.parse(JSON.stringify(row)));
      this.westMedicineSearchQuery = '';
      this.showWestTable = false;
    },

    handleSelChinaTableRowClick(row) {
      delete row.id;
      row.chsCode = row.purcDate;
      row.saleUnt = 1;
      row.tableId = row.phayId;
      row.unt = row.minUnt;
      row.sdoseUnt = row.dosUnt;
      this.chinaChekeCurrentData = {...row};
      this.chinaMedicineSearchQuery = row.drugName;
      this.showChinaTable = false;
      this.$nextTick(() => {
        this.$refs.dosageInput && this.$refs.dosageInput.focus();
      });
      /*this.chinaMedicineTableData.push(row);
      console.log(this.chinaMedicineTableData,'this.chinaMedicineTableDatathis.chinaMedicineTableData')*/

    },

    handleCancelSelDiagnose() {
      this.westernSelectedTable = [];
      this.westernDiagnosisModalVisible = false;
      this.chinaSelectedTable = [];
      this.chinaDiagnosisModalVisible = false;
      this.selChinaDiagnosis = {};
      this.westernSearchQuery = '';
      this.chinaSearchQuery1 = '';
      this.chinaSearchQuery2 = '';
    },

    async addReceptionDiagnosis(val) {
      await withLoading(this, '数据提交中...')(async () => {
        switch (val) {
          case 1: // 西药诊断
            if (this.westernSelectedTable.length <= 0) {
              this.$message.warning("请至少选择一项西药诊断!");
              return;
            }

            this.westernSelectedTable = this.westernSelectedTable.map(item => ({
              ...item,
              name: item.name.replace(/\?/g, ''),
              diagnosticCategory: '1',
              seeDoctorId: this.patientChooseForm.seeDoctorId,
              insuranceCode: item.chsCode,
              insuranceName: item.chsName,
              diagnosticName: item.name,
              icdCode: item.code,
              remark: item.remarks,
            }));

            const res = await editReceptionDiagnosis(this.westernSelectedTable);
            if (res.code === 200) {
              this.westernDiagnosisModalVisible = false;
              this.addSeedoctorForm.westernDiagnos = '';
              const diagnosticNames = this.westernSelectedTable.map(item => `(${item.diagnosticName})`).join(' ');

              this.addSeedoctorForm = {
                ...this.addSeedoctorForm,
                westernDiagnos: diagnosticNames
              };

              const res2 = await editReception({
                id: this.patientChooseForm.seeDoctorId,
                westernDiagnos: diagnosticNames,
              });

              if (res2.code !== 200) {
                this.$message.error(res2.message);
              }

              this.westernSelectedTable = [];
              this.$message.success('西药诊断保存成功');
            } else {
              throw new Error(res.message || '西药诊断保存失败');
            }
            break;

          case 2: // 中药诊断
            if (this.chinaSelectedTable.length <= 0) {
              this.$message.warning("请至少选择一项中药诊断!");
              return;
            }

            this.chinaSelectedTable = this.chinaSelectedTable.map(item => ({
              ...item,
              diagnosticName: item.insuranceName + '-' + item.chineseSyndromeName,
              diagnosticCategory: '2',
              seeDoctorId: this.patientChooseForm.seeDoctorId,
            }));
            console.log(this.chinaSelectedTable, 'this.chinaSelectedTablethis.chinaSelectedTablethis.chinaSelectedTable')

            const chinaRes = await editReceptionDiagnosis(this.chinaSelectedTable);
            if (chinaRes.code === 200) {
              this.selChinaDiagnosis = {};
              this.chinaDiagnosisModalVisible = false;
              this.addSeedoctorForm.chinaDiagnose = '';
              const diagnosticNames = this.chinaSelectedTable.map(item => `(${item.diagnosticName})`).join(' ');

              this.addSeedoctorForm = {
                ...this.addSeedoctorForm,
                chinaDiagnose: diagnosticNames
              };

              const chinaRes2 = await editReception({
                id: this.patientChooseForm.seeDoctorId,
                chinaDiagnose: diagnosticNames,
              });

              if (chinaRes2.code !== 200) {
                this.$message.error(chinaRes2.message);
              }

              this.chinaSelectedTable = [];
              this.$message.success('中药诊断保存成功');
            } else {
              throw new Error(chinaRes.message || '中药诊断保存失败');
            }
            break;
        }
      });
    },

    resetDiagnoseData(val) {
      switch (val) {
        case 1:
          this.westernSearchQuery = '';
          this.getWesternDiagnosisData();
          break;
        case 2:
          this.chinaSearchQuery1 = '';
          this.getChinaDiagnosisOptions();
          break;
        case 3:
          this.chinaSearchQuery2 = '';
          this.getChinaDiagnosisOptions();
          break;
      }

    },

    removeWesternSelected(index) {
      this.westernSelectedTable.splice(index, 1)
    },

    removeChinaSelected(index) {
      this.chinaSelectedTable.splice(index, 1)
    },

    removeDoctordisposeSelected(index) {
      this.doctordisposeTableData.splice(index, 1)
    },

    removeWestMedicineTableData(index) {
      console.log(index, 'indexindexindexindex');

      const hasAdviceId = this.medicalAdviceData.some(item => item.adviceId !== null);
      console.log(hasAdviceId, 'indexindexindexindex');
      if (hasAdviceId) {
        const currentItem = this.westMedicineTableData[index];
        console.log(currentItem, 'currentItemcurrentItemcurrentItem');
        if (!currentItem.adviceId) {
          this.westMedicineTableData.splice(index, 1); // 直接 splice 会触发 watch
        } else {
          this.$message.warning("已开处方请在医嘱列表删除!");
        }
      } else {
        this.westMedicineTableData.splice(index, 1); // 直接 splice 会触发 watch
      }

      // 不再需要 this.$forceUpdate();
    },

    async handleWesternSearch() {
      const res = await getDocticdList({pageSize: 100, condition: this.westernSearchQuery});
      this.westernDiagnosisTableData = res.data.map(item => {
        return {
          ...item,
          definiteDiagnosis: 0,
        }
      })
    },

    async handleChinaSearch(val) {
      if (val === 1) {
        const res = await getChinaDiseaseByCondition({pageSize: 100, condition: this.chinaSearchQuery1});
        this.chinaDiagnosisTableData1 = res.data;
        return;
      }

      const res = await getSyndromeByCondition({pageSize: 100, condition: this.chinaSearchQuery2});
      this.chinaDiagnosisTableData2 = res.data;
    },

    async addToWesternSelectedTable(row) {
      // 创建新对象以避免修改原始数据
      const newRow = {
        ...row,
        name: row.name,  // 添加问号标记
        originalName: row.name,    // 保存原始名称
        definiteDiagnosis: 1
      };

      const res = this.westernSelectedTable.findIndex(item => item.id === newRow.id);
      if (res === -1) {
        this.westernSelectedTable.push(newRow);
        return;
      }

      console.log(this.westernSelectedTable, 'westernSelectedTable');
      this.$message.error(`(${newRow.name}) 已存在,请勿重复添加!`);
    },

    async addToChinaSelectedTable(row) {
      if (!this.selChinaDiagnosis || Object.keys(this.selChinaDiagnosis).length === 0) return this.$message.error(`请添加新的数据!`);
      const isExist = this.chinaSelectedTable.some(item =>
          item.diseaseCode === this.selChinaDiagnosis.code &&
          item.chineseSyndromeCode === row.code
      );
      if (!isExist) {
        const newItem = {
          id: this.selChinaDiagnosis.id,
          syndromeId: row.id,
          diagnosticName: this.selChinaDiagnosis.name,
          diseaseCode: this.selChinaDiagnosis.code,
          chineseSyndromeCode: row.code,
          chineseSyndromeName: row.name,
          icdCode: this.selChinaDiagnosis.code,
          insuranceName: this.selChinaDiagnosis.chsName,
          insuranceCode: this.selChinaDiagnosis.chsCode,
          syndromeName: row.chsName,
          syndromeCode: row.chsCode,
        };
        this.chinaSelectedTable.push(newItem);
        return;
      }

      console.log(this.chinaSelectedTable, 'chinaSelectedTablechinaSelectedTable')
      this.$message.error(`"${this.selChinaDiagnosis.name} + ${row.name}" 组合已存在，请勿重复添加！`);
    },

    async selChinaDiagnosisRow(row) {
      this.selChinaDiagnosis = row;
      console.log(this.selChinaDiagnosis, 'this.selChinaDiagnosisthis.selChinaDiagnosisthis.selChinaDiagnosis')
      console.log(this.chinaSelectedTable, 'this.selChinaDiagnosisthis.selChinaDiagnosisthis.selChinaDiagnosis')
    },

    handleRefreshTable() {
      this.loadData();
      setTimeout(() => {
        this.$message.success(`已成功刷新待诊病人${this.tableData1.length}人,接诊病人${this.tableData2.length}人`)
      }, 500);
    },

    async handleAddFastReception(options = {}) {
      await withLoading(this, '数据处理中...')(async () => {
        try {
          const {
            patientForm,
            receptionForm,
            tableData2,
            registerOptions,
            userInfo,
            $refs: { patientFormRef },
            $message,
            $options
          } = this;
          const patientId = patientForm.id;

          // 前置验证
          if (tableData2.some(({patientId: pid}) => pid === patientId)) {
            return $message.warning("该患者已在就诊列表,请选择直接进行操作!");
          }
          if (!receptionForm.regTypeId) {
            return $message.warning("请选择挂号类别!");
          }
          if (!options.skipValidation && !(await patientFormRef.validate())) {
            return;
          }

          // 优化数据处理
          const lastCode = arr => arr?.slice(-1)[0] || '';
          patientForm.naplAddCode = lastCode(patientForm.naplAddCodeArr);
          patientForm.conerAddCode = lastCode(patientForm.conerAddCodeArr);
          patientForm.thrNot = patientForm.thrNot ? 1 : 0;

          // 优化对象合并
          const regType = registerOptions.find(item => item.id === receptionForm.regTypeId);
          Object.assign(receptionForm, {
            address: `${patientForm.conerAddJoinName}${patientForm.conerAddName}`,
            age: patientForm.ageYear,
            gender: patientForm.sex,
            doctorId: userInfo.staffId,
            deptId: userInfo.selDept,
            patientId,
            patientName: patientForm.name,
            cardid: patientForm.certno,
            pregnant: patientForm.pregnant ? 1 : 0,
            regTypeName: regType?.label
          });

          // 优化API调用
          const isNewPatient = patientId == null;
          const [apiMethod, action] = isNewPatient
              ? [addDocphr, '新增']
              : [editDocphr, '更新'];

          const res2 = await apiMethod(patientForm);
          if (res2.code !== 200) {
            return $message.error(`${action}健康档案失败!`);
          }

          if (isNewPatient) {
            receptionForm.patientId = res2.data;
          }

          const res1 = await addFastReception(receptionForm);
          if (res1.code !== 200) {
            return $message.error("快速接诊失败!");
          }

          // 并行加载数据和处理结果
          await Promise.all([
            this.loadData(),
            this.handleClickReceptionRow({
              ...patientForm,
              ...receptionForm,
              id: res1.data
            }, 1)
          ]);

          // 重置表单
          this.receptionForm = Object.assign({}, $options.data.call(this).receptionForm);
          this.receptionModalVisible = false;

        } catch (error) {
          console.error('快速接诊系统异常:', error);
          this.$message.error("系统异常:请联系管理员");
        }
      });
    },

    async handleSearch() {
      const res = await getDocphrByCondtion({condtion: this.patientForm.patId});
      if (res.data.length > 1) {
        this.patientDialogVisible = true;
        this.patientTabelData = res.data;
        this.isInputDisabled = this.patientForm.patId != null;
        return;
      } else if (res.data.length <= 0) {
        this.$message.warning("没有搜索到相关患者!请在健康档案新增或挂号菜单快速建档!")
        return;
      }
      this.patientChooseForm = res.data[0];
      await this.handleChoosePatient();
      this.isInputDisabled = this.patientForm.patId != null;
    },

    handleRegTypePrice(val) {
      this.receptionForm.price = this.registerOptions.find(item => item.id === val).odcost;
    },

    async handleFastReceptionClick() {
      this.conerPleasett = '';
      this.naplPleasett = '';
      this.patientForm = Object.assign({}, this.$options.data.call(this).patientForm)
      await this.getRegisterType();
      const mainRegType = this.registerOptions.find(item => item.mainType = 1);
      if (this.registerOptions.length < 1) return this.$message.warning("请去添加挂号类别")
      this.receptionForm.regTypeId = mainRegType.id;
      this.receptionForm.price = mainRegType.odcost;
      this.isInputDisabled = false;
      this.receptionModalVisible = true;
    },

    handleReceptionClick(row, column, event) {
      event.preventDefault();
      this.showReception = true;
      this.contextMenuLeft = event.clientX;
      this.contextMenuTop = event.clientY;
      this.ReceptionRowData = row;
      document.addEventListener('click', this.closeContextMenu);
    },

    handleWestGroupsFixed(row, column, event) {
      event.preventDefault();
      const selectedRows = this.$refs.westMedicineTableData.selection;
      const isSelected = selectedRows.some(selectedRow => selectedRow.id === row.id);

      if (!isSelected) {
        // 如果未选中，阻止右键菜单显示
        event.preventDefault();
        return;
      }

      // 如果选中，显示右键菜单
      this.showWestGroupsClick = true;
      this.contextMenuLeft = event.clientX;
      this.contextMenuTop = event.clientY;
      document.addEventListener('click', this.closeContextMenu);
    },

    handleCancelReceptionClick(row, column, event) {
      event.preventDefault();
      this.showCancelReception = true;
      this.contextMenuLeft = event.clientX;
      this.contextMenuTop = event.clientY;
      this.ReceptionRowData = row;
      document.addEventListener('click', this.closeContextMenu);
    },

    closeContextMenu() {
      this.showReception = false;
      this.showCancelReception = false;
      this.showAdviceRightClick = false;
      this.showWestGroupsClick = false;
      // 移除事件监听
      document.removeEventListener('click', this.closeContextMenu);
    },

    handleAdviceRightClick(row, column, event) {
      if (row.orderType === 5) return;
      event.preventDefault();
      this.showAdviceRightClick = true;
      this.contextMenuLeft = event.clientX;
      this.contextMenuTop = event.clientY;
      this.adviceRightClickRow = row;
      document.addEventListener('click', this.closeContextMenu);
    },

    handleMenuClick(action) {
      this.closeContextMenu();
      switch (action) {
        case 1 :
          this.handleSitIn(this.ReceptionRowData);
          this.loadData();
          break;
        case 2 :
          this.handlieCancelReception(this.ReceptionRowData)
          this.loadData();
          break;
        case 3 :
          this.handlieSucceedReception(this.ReceptionRowData);
          break;
        case 4:
          this.delOneAdvice(this.adviceRightClickRow);
          break;
        case 5:
          this.createWestGroupsCode();
          break;
        case 6:
          this.clearWestGroupsCode();
          break;
        case 7:
          this.batchDelOneAdvice();
          break;
      }

    },

    async handlieSucceedReception(row) {
      try {
        // 1. 添加确认对话框
        const confirmResult = await this.$confirm(
            `患者(${row.patientName}):是否确认完成就诊该患者`,
            '操作确认',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        ).catch(() => {
          return false;
        });

        if (!confirmResult) return;
        const newItem = {
          id: row.id,
          status: 4,
        };
        const res = await editReception(newItem);
        if (res.code === 200) {
          this.handleCancelContract();
          await this.loadData();
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        this.$message.error("系统异常:请联系管理员");
      }
    },

    async handlieCancelReception(row) {
      try {
        // 1. 添加确认对话框
        await this.$confirm(`患者(${row.patientName}):是否确认取消就诊该患者`, '取消就诊确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false // 防止误触
        });
        console.log(this.medicalAdviceData, 'this.medicalAdviceDatathis.medicalAdviceDatathis.medicalAdviceData')
        if (this.medicalAdviceData.some(item => item.status === 2)) {
          this.$message.warning("该患者已缴费,无法取消接诊")
          return;
        }

        // 2. 用户确认后执行原逻辑
        let params = {};
        if (row.type === '1') {
          params = {
            dregisterTableId: row.dregisterTableId,
            id: row.id
          };
        } else {
          params = {id: row.id};
        }

        const res = await getReceptionCancel(params);

        // 3. 处理结果
        if (res.code === 200) {
          this.ReceptionRowData = null;
          this.patientForm = Object.assign({}, this.$options.data.call(this).patientForm)
          const res2 = await getReceptionList({doctorId: this.userInfo.staffId, status: 1});
          this.tableData2 = res2.data;
          const sortedData = [...this.tableData1]?.sort((a, b) => {
            return new Date(a.regTime) - new Date(b.regTime);
          });
          sortedData?.map((item, index) => {
            item.optTime = item.optTime.substring(5);
            item.regDeptName = this.deptOptions?.find(dept => dept.id === item.regDepId)?.label ?? '';
            item.order = index + 1;
          })
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        // 用户点击取消或请求失败
        if (error !== 'cancel') { // 排除用户主动取消的情况
          console.error('取消就诊失败:', error);
          this.$message.error("操作过程中发生错误");
        }
      }
    },

    async handleSitIn(row) {
      this.receptionForm.doctorId = row.regDoctorId;
      this.receptionForm.dregisterTableId = row.id;
      this.receptionForm.patientId = row.patientId;
      this.receptionForm.patientName = row.name;
      this.receptionForm.age = row.age;
      this.receptionForm.deptId = this.userInfo.selDept;
      const res = await addReception(this.receptionForm)
      if (res.code === 200) {
        this.showReception = false;
        await this.loadData();
      } else {
        this.$message.error(res.message)
      }
    },

    handleBlur() {
      setTimeout(() => {
        this.showPatientTellSelect = false;
        this.showNowHistorySelect = false;
        this.showBeforeHistorySelect = false;
      }, 500);
    },

    async handleAiseAddOrEdit() {
      try {
        const valid = await this.$refs.aiseFormRef.validate();
        if (!valid) {
          this.$message.warning('请填写完整表单');
          return;
        }
        await withLoading(this, '数据提交中...')(async () => {
          let res;
          if (!this.aiseForm.id) {
            res = await addAise(this.aiseForm);
          } else {
            res = await editAise(this.aiseForm);
          }
          if (res.code === 200) {
            await this.getAiseList();
            this.aiseAddOrEditMedicineDialog = false;
          } else {
            this.$message.error(res.message)
          }
        });
      } catch (error) {
      } finally {

      }
    },

    async handleAddTemplate() {
      await withLoading(this, '数据提交中...')(async () => {
        // 1. 表单验证
        const valid = await this.$refs.templateFormRef.validate();
        if (!valid) {
          this.$message.warning('请填写完整表单');
          return;
        }

        // 2. 根据模板类型处理
        switch (this.templateType) {
          case 1:
            const apiCall = this.templateForm.id
                ? editComplainTemplate
                : addComplainTemplate;

            const res1 = await apiCall(this.templateForm);

            if (res1.code === 200) {
              this.tpAddOrEditMedicineDialog = false;
              this.templateForm = Object.assign({}, this.$options.data.call(this).templateForm)
              const options1 = await getComplainTemplate({
                pageSize: 100,
                pageNum: 1,
                state: 1,
                condition: '',
                deptId: this.userInfo.selDept
              });
              this.complainTemplateOptions = options1.data.content.map(item => ({
                label: item.content,
                id: item.id,
                data: item
              }));
            } else {
              this.$message.error(res1.message)
            }
            break;

          case 2: // 现病史模板
            const apiCall2 = this.templateForm.id
                ? editNowHistoryTemplate
                : addNowHistoryTemplate;

            const res2 = await apiCall2(this.templateForm);
            if (res2.code === 200) {
              this.tpAddOrEditMedicineDialog = false;
              this.templateForm = Object.assign({}, this.$options.data().templateForm);
              const options2 = await getNowHistoryTemplate({
                pageSize: 100,
                pageNum: 1,
                state: 1,
                condition: '',
                deptId: this.userInfo.selDept
              });
              this.nowHistoryTemplateOptions = options2.data.content.map(item => ({
                label: item.content,
                id: item.id,
                data: item
              }));
            } else {
              this.$message.error(res2.message)
            }
            break;

          case 3: // 既往史模板
            const apiCall3 = this.templateForm.id
                ? editBeforeHistoryTemplate
                : addBeforeHistoryTemplate;

            const res3 = await apiCall3(this.templateForm);
            if (res3.code === 200) {
              this.tpAddOrEditMedicineDialog = false;
              this.templateForm = Object.assign({}, this.$options.data().templateForm);
              const options3 = await getBeforeHistoryTemplate({
                pageSize: 100,
                pageNum: 1,
                state: 1,
                condition: '',
                deptId: this.userInfo.selDept
              });
              this.beforeHistoryTemplateOptions = options3.data.content.map(item => ({
                label: item.content,
                id: item.id,
                data: item
              }));
            } else {
              this.$message.error(res3.message)
            }
            break;
        }
      });
    },

    handleEditAllTemplate(val, data) {
      this.tpAddOrEditMedicineDialog = true;
      this.templateForm = data.data;
      this.templateForm.state = parseInt(this.templateForm.state)

      switch (val) {
        case 1:
          this.templateAddRrEditTtiel = "编辑主诉模板";
          this.templateType = 1;
          break;

        case 2:
          this.templateAddRrEditTtiel = "编辑现病史模板";
          this.templateType = 2;
          break;

        case 3:
          this.templateAddRrEditTtiel = "编辑既往史模板";
          this.templateType = 3;
          break;
      }
    },

    handleAddAllTemplate(val) {
      this.tpAddOrEditMedicineDialog = true;
      switch (val) {
        case 1:
          this.templateAddRrEditTtiel = "新增主诉模板";
          this.templateType = 1;
          break;

        case 2:
          this.templateAddRrEditTtiel = "新增现病史模板";
          this.templateType = 2;
          break;

        case 3:
          this.templateAddRrEditTtiel = "新增既往史模板";
          this.templateType = 3;
          break;
      }
    },

    async choosePatientTell(data) {
      const newItem = {
        ...this.patientForm,
        pregnant: this.patientForm.pregnant ? 1 : 0,
        id: this.patientChooseForm.seeDoctorId,
        patientTell: this.addSeedoctorForm.patientTell,
      }
      if (this.addSeedoctorForm.patientTell?.trim()) {
        const res = await editReception(newItem);
        if (res.code !== 200) {
          this.$message.error(res.message);
        }
      }
    },

    async chooseNowHistory(data) {
      const newItem = {
        ...this.patientForm,
        pregnant: this.patientForm.pregnant ? 1 : 0,
        id: this.patientChooseForm.seeDoctorId,
        nowHistory: this.addSeedoctorForm.nowHistory,
      }
      if (this.addSeedoctorForm.nowHistory?.trim()) {
        const res = await editReception(newItem);
        if (res.code !== 200) {
          this.$message.error(res.message);
        }
      }
    },

    async chooseBeforeHistory(data) {
      const newItem = {
        ...this.patientForm,
        pregnant: this.patientForm.pregnant ? 1 : 0,
        id: this.patientChooseForm.seeDoctorId,
        beforeHistory: this.addSeedoctorForm.beforeHistory,
      }
      if (this.addSeedoctorForm.beforeHistory?.trim()) {
        const res = await editReception(newItem);
        if (res.code !== 200) {
          this.$message.error(res.message);
        }
      }
    },

    async switchToSelect(value) {
      if (!this.preVerificationUserInfo()) return;
      switch (value) {
        case 1:
          this.showPatientTellSelect = true
          this.$nextTick(() => {
            this.$refs.showPatientTellSelect.focus()
          })
          if (this.complainTemplateOptions.length > 0) return;
          const res1 = await getComplainTemplate({
            pageSize: 500,
            pageNum: 1,
            state: 1,
          });
          this.complainTemplateOptions = res1.data.content.map(item => {
            return {
              label: item.content, id: item.id, data: item
            }
          })
          break;

        case 2:
          this.showNowHistorySelect = true
          this.$nextTick(() => {
            this.$refs.showNowHistorySelect.focus()
          })
          if (this.nowHistoryTemplateOptions.length > 0) return;
          const res2 = await getNowHistoryTemplate({
            pageSize: 500,
            pageNum: 1,
            state: 1,
          });
          this.nowHistoryTemplateOptions = res2.data.content.map(item => {
            return {
              label: item.content, id: item.id, data: item
            }
          })
          break;

        case 3:
          this.showBeforeHistorySelect = true
          this.$nextTick(() => {
            this.$refs.showBeforeHistorySelect.focus()
          })
          if (this.beforeHistoryTemplateOptions.length > 0) return;
          const res3 = await getBeforeHistoryTemplate({
            pageSize: 500,
            pageNum: 1,
            state: 1,
          });
          this.beforeHistoryTemplateOptions = res3.data.content.map(item => {
            return {
              label: item.content, id: item.id, data: item
            }
          })
          break;
      }


    },

    /*handleDelItemPrice(){
      this.doctordisposeTableData.filter(item => item.id !== this.currentSelectedRow.id);
      console.log(this.currentSelectedRow)
      this.medicalAdviceData = this.medicalAdviceData.filter(
          item => !(item.id === this.currentSelectedRow.id && item.type === "处置项目")
      );
    },*/

    async handleConfirmDisposeItem() {
      await withLoading(this, '数据提交中...')(async () => {
        const requestData = this.doctordisposeTableData.map(item => ({
          ...item,
          costnameId: item.id,
          dregisterId: this.patientChooseForm.dregisterTableId,
          name: this.patientForm.name,
          num: item.count,
          openDeptId: this.userInfo.selDept,
          seeDoctorId: this.patientChooseForm.seeDoctorId,
          staffId: this.userInfo.staffId, //this.userInfo.userId;
          bsSource: 4,
          chargeStatus: item.chargeStatus ? item.chargeStatus : 0,
          dataSource: 1,
          executionAmount: item.executeOdcost,
          executionPrice: item.odcost,
          remark: item.remarks,
          standardPrice: item.odcost,
          patientId: this.patientForm.id,
          age: this.patientForm.ageYear,
          brdy: this.patientForm.brdy,
          careateId: this.userInfo.staffId, //this.userInfo.userId;
        }))
        const res = await addDoctordispose(requestData);
        if (res.code === 200) {
          this.doctordisposeTableData = [];
          this.selDoctordisposeDialog = false;
          await this.resetDisposeAndAdviceData();
        } else {
          this.$message.error(res.message);
        }
      });
    },

    async handleConfirmWest() {
      if (this.addWesternForm.phayId === null) {
        this.$message.warning("请选择取药药房!")
        this.$nextTick(() => {
          this.$refs.westPharmacySelect.focus();
        });
        return;
      }
      await withLoading(this, '数据提交中...')(async () => {
        this.addWesternForm.adviceId = this.westMedicineTableData[0].adviceId;
        this.addWesternForm.id = this.westMedicineTableData[0].westPrescriptionId;
        this.addWesternForm.agnterCertType = this.patientForm.identityCard;
        this.addWesternForm.bilgDeptId = this.userInfo.selDept; //this.userInfo.depts
        this.addWesternForm.bilgDrId = this.userInfo.staffId; //this.userInfo.userId;
        this.addWesternForm.bilgOptId = this.userInfo.staffId;
        this.addWesternForm.icdCode = this.westernSelectedTable.map(item => item.code).join(',');
        this.addWesternForm.name = this.patientForm.name;
        this.addWesternForm.brdy = this.patientForm.brdy;
        this.addWesternForm.patientId = this.patientForm.id;
        this.addWesternForm.seeId = this.patientChooseForm.seeDoctorId
        this.addWesternForm.pricingType = 1;
        this.addWesternForm.state = 0;
        this.addWesternForm.age = this.patientForm.ageYear;
        this.addWesternForm.ageVar = this.patientForm.ageYear + '岁' + this.patientForm.ageMonth + '月';
        this.addWesternForm.icdName = this.westernSelectedTable.map(item => item.name).join(', ');
        this.addWesternForm.opspRx = this.addWesternForm.opspRx === false ? 0 : 1;
        this.addWesternForm.regId = this.patientChooseForm.dregisterTableId;
        this.addWesternForm.remark = this.westernMedicineForm.remark;
        this.addWesternForm.status = 1;
        this.addWesternForm.sex = this.patientForm.sex;
        this.addWesternForm.saleAmt = this.westMedicineTableData
            .reduce((total, item) => total + (Number(item.saleAmt) || 0), 0)
            .toFixed(2);
        this.addWesternForm.dugDrxDetailsVOS = JSON.parse(JSON.stringify(this.westMedicineTableData));

        console.log(this.addWesternForm, 'this.addWesternFormthis.addWesternFormthis.addWesternForm')
        const hasId = this.westMedicineTableData.some(item => item.id);
        let res;
        if (hasId) {
          res = await editWestPrescription(this.addWesternForm); // 调用修改接口
        } else {
          res = await addWestPrescription(this.addWesternForm); // 调用新增接口
        }
        if (res.code === 200) {
          if (this.addWesternForm.isWestPrint) {
            await this.printWestPrescription(res.data);
          }
          await this.handleEditDocphr();
          await this.resetWestMedicineData();
        } else {
          this.$message.error("请检查西药处方:"+res.message);
        }
      });
    },

    async handleConfirmChina() {
      if (this.addChinaForm.phayId === null) {
        this.$message.warning("请选择取药药房!")
        this.$nextTick(() => {
          this.$refs.chinaPharmacySelect.focus();
        });
        return;
      }
      await withLoading(this, '数据提交中...')(async () => {
        this.addChinaForm.bilgDeptId = this.userInfo.selDept;
        this.addChinaForm.bilgDrId = this.userInfo.userId;
        this.addChinaForm.name = this.patientForm.name;
        this.addChinaForm.regId = this.patientChooseForm.dregisterTableId;
        this.addChinaForm.seeId = this.patientChooseForm.seeDoctorId;
        this.addChinaForm.tcmDetailsVOS = JSON.parse(JSON.stringify(this.chinaMedicineTableData));
        this.addChinaForm.tcmDetailsVOS = this.addChinaForm.tcmDetailsVOS.map(item => ({
          ...item,
          roundUnt: 2,
          tcmCnt: item.sdoseCnt * this.addChinaForm.tcmCnt,
          medcWayId: this.addChinaForm.medcWayId,
          usedfrquId: this.addChinaForm.usedfrquId,
          sdoseSum: item.sdoseCnt * this.addChinaForm.tcmCnt
        }));
        console.log(this.addChinaForm.tcmDetailsVOS, 'this.addChinaForm.tcmDetailsVOSthis.addChinaForm.tcmDetailsVOS')
        this.addChinaForm.tcmWayName = this.tcmwayOptions.find(item => item.id === this.addChinaForm.tcmWayId).label;
        this.addChinaForm.opspRx = this.addChinaForm.opspRx ? 1 : 0;
        this.addChinaForm.age = this.patientForm.ageYear;
        this.addChinaForm.ageVar = this.patientForm.ageYear + '岁' + this.patientForm.ageMonth + '月';
        this.addChinaForm.icdCode = this.chinaSelectedTable
            .map(item => item.icdCode)
            .join(', ');
        this.addChinaForm.icdName = this.chinaSelectedTable[0]?.diagnosticName;
        this.addChinaForm.pricingType = 1;
        this.addChinaForm.brdy = this.patientForm.brdy;
        this.addChinaForm.patientId = this.patientForm.id;
        this.addChinaForm.seeId = this.patientChooseForm.seeDoctorId
        this.addChinaForm.purcAmt = this.chinaMedicineTableData.reduce(
            (sum, item) => sum + (Number(item.purcPric) || 0),
            0
        );
        this.addChinaForm.rxType = 1;
        this.addChinaForm.saleAmt = this.chinaMedicineTableData.reduce(
            (sum, item) => sum + (Number(item.minSalePric) || 0),
            0
        );
        this.addChinaForm.sex = this.patientForm.sex;
        this.addChinaForm.state = 0;
        this.addChinaForm.useMethod = [
          this.addChinaForm.takeMedicineWay1,
          this.addChinaForm.takeMedicineWay2
        ].filter(Boolean).join(',');

        const hasId = this.chinaMedicineTableData.some(item => item.id); // 检查是否有id字段
        let res;
        if (hasId) {
          this.addChinaForm.tcmDetailsVOS = this.addChinaForm.tcmDetailsVOS.map(item => ({
            ...item, id: null
          }));
          console.log(this.addChinaForm, 'this.addChinaFormthis.addChinaFormthis.addChinaForm')
          res = await editChinaPrescription(this.addChinaForm); // 调用修改接口
        } else {
          res = await addChinaPrescription(this.addChinaForm); // 调用新增接口
        }

        if (res.code === 200) {
          this.chinaMedicineUsageDialog = false;
          if (this.addChinaForm.isChinaPrint) {
            await this.printChinaPrescription(res.data);
          }
        } else {
          this.$message.error(res.message);
          return;
        }

        await this.handleEditDocphr();
        this.chinaMedicineTableData = [];
        const [res2, res5] = await Promise.all([
          getReceptionDiagnosis({category: 2, seeDoctorId: this.patientChooseForm.seeDoctorId}),
          getDoctoradvice({seeDoctorId: this.patientChooseForm.seeDoctorId}),
        ]);
        this.medicalAdviceData = res5.data;
        this.addSeedoctorForm = {
          ...this.addSeedoctorForm,
          chinaDiagnose: res2.map(item => `(${item.diagnosticName})`).join('') || '',
          chinaPrescription: res5.data
              .filter(item => item.orderType === 1)
              .map(item => item.content.split(',').join('\n'))
              .join('\n') || '',
        };
        this.addChinaForm = Object.assign({}, this.$options.data.call(this).addChinaForm);
        this.selChineseMedicineDialog = false;
      });
    },

    handleCloseDoctordisposeTabel() {
      this.doctordisposeTableData = [];
      this.isShowPrescription = false;
      this.selDoctordisposeDialog = false;
    },


    handleCloseChinaTabel() {
      this.chinaMedicineSearchQuery = '';
      this.addChinaForm = Object.assign({}, this.$options.data.call(this).addChinaForm);
      this.chinaMedicineUsageDialog = false;
      /*if (this.$refs.chinaMedicineTable) {
        this.$refs.chinaMedicineTable.clearSelection();
      }*/
    },

    async handleDisposeData(isFrequency = false) {
      try {
        const res = await getChargingPriceById(this.searchForm.chargingPriceId);
        const res2 = await getDoctordispose({seeDoctorId: this.patientChooseForm.seeDoctorId});

        // 检查是否存在重复医嘱
        if (res2.data.some(item => item.costnameId === res.data.id) && !isFrequency) {
          // 使用确认对话框替代原来的简单提示
          try {
            await this.$confirm(
                `处置医嘱:【${res.data.costname}】已存在医嘱列表，是否继续生成？`,
                '重复医嘱提示',
                {
                  confirmButtonText: '继续生成',
                  cancelButtonText: '取消',
                  type: 'warning'
                }
            );
            // 用户点击"继续生成"，继续执行后面的代码
          } catch (cancel) {
            // 用户点击"取消"或关闭对话框
            this.$message.info('已取消生成重复医嘱');
            return;
          }
        }

        // 如果是执行频次模式且需要选择频次
        if (res.data.executemode === 1 && !isFrequency) {
          this.selExecutionPLDialogVisible = true;
          return;
        }

        if (this.searchForm.executionDays < 1 || this.searchForm.executionDays === null) {
          this.$message.warning("请填写正确的频率天数!");
          return;
        }

        console.log(this.searchForm.deptName, 'searchForm.deptNamesearchForm.deptName');

        const itemData = {
          ...res.data,
          remark: this.searchForm.remark,
          deptName: this.searchForm.deptName,
          doctorName: this.userInfo.staffName,
          frquCnt: this.searchForm.executionNum,
          prdDays: this.searchForm.executionDays,
          executDeptId: this.searchForm.depexecutetype,
          sex: this.patientForm.sex,
          executeOdcost: this.searchForm.executionNum * this.searchForm.odcost,
          count: this.searchForm.count,
          ...(isFrequency && {exeFrquId: this.searchForm.usedfrquId})
        };

        console.log(itemData, 'itemData.itemData.itemDataitemDataitemDataitemDataitemData');

        // 添加到表格
        this.doctordisposeTableData.push(itemData);

        // 重置表单
        this.searchForm = Object.assign({}, this.$options.data.call(this).searchForm);

        // 关闭弹窗（如果是频次模式）
        if (isFrequency) {
          this.selExecutionPLDialogVisible = false;
        }

        console.log('当前处置表数据:', this.doctordisposeTableData);
      } catch (error) {
        console.error('处理数据出错:', error);
        // 这里要区分是确认框的取消还是其他错误
        if (error !== 'cancel') {
          this.$message.error('操作失败，请重试');
        }
      }
    },

    getChargingPriceDetail(val) {
      // 处理空值情况
      if (val == null || val === '') {
        this.searchForm.odcost = null;
        this.searchForm.deptName = '';
        this.searchForm.remark = '';
        return;
      }

      const isExist = this.doctordisposeTableData.some(item => item.id === val);
      if (isExist) {
        this.$message.warning("请勿重复选择!")
        this.searchForm.odcost = null;
        this.searchForm.deptName = '';
        this.searchForm.remark = '';
        return;
      }
      // 查找匹配的收费项目
      const chargingPrice = this.chargingPriceOptions.find(item => item.id === val);

      // 检查是否找到收费项目
      if (!chargingPrice) {
        this.$message.error('系统异常:未找到对应的收费项目!')
        return;
      }
      if (chargingPrice.depexecutetype === 1 || chargingPrice.depexecutetype === 2) {
        this.searchForm.deptName = chargingPrice.depexecutetype === 1
            ? (this.deptOptions.find(item => item.id === this.userInfo.selDept)?.id || '')
            : this.userInfo.selDept;
      } else if (chargingPrice.depexecutetype === 0) {
        const executeDept = this.deptOptions.find(item => item.id === chargingPrice.executedepid);
        if (executeDept) {
          this.searchForm.deptName = executeDept.id;
        }
      }

      // 设置表单值
      this.searchForm.odcost = chargingPrice.odcost;
      this.searchForm.depexecutetype = chargingPrice.depexecutetype;


    },

    async getChargingPrice() {
      if (this.chargingPriceOptions.length > 0) return;
      const res = await getChargingPrice({state: 1});
      this.chargingPriceOptions = res.data.map(item => {
        return {
          id: item.id, label: item.costname, odcost: item.odcost,
          executedepid: item.executedepid, depexecutetype: item.depexecutetype, executemode: item.executemode,
        }
      })
    },

    async getChinaDiagnosisOptions(type) {
      // 前置条件验证
      if (!this.preVerificationUserMedical()) return;


      await withLoading(this, '数据加载中...')(async () => {
        const [icdList, syndromeList, diagnoses] = await Promise.all([
          getChinaDocticdList(),
          getSyndromeList(),
          getReceptionDiagnosis({category: 2, seeDoctorId: this.patientChooseForm.seeDoctorId})
        ]);

        // 处理返回数据
        this.chinaSelectedTable = diagnoses.map(({
                                                   diagnosticName,
                                                   diseaseCode,
                                                   chineseSyndromeCode,
                                                   chineseSyndromeName,
                                                   insuranceName,
                                                   insuranceCode,
                                                   syndromeName,
                                                   syndromeCode
                                                 }) => ({
          diagnosticName,
          diseaseCode,
          chineseSyndromeCode,
          chineseSyndromeName,
          insuranceName,
          insuranceCode,
          syndromeName,
          syndromeCode
        }));

        this.chinaDiagnosisTableData1 = icdList.data;
        this.chinaDiagnosisTableData2 = syndromeList.data;

        // 条件性显示弹窗
        if (type !== 1) {
          this.chinaDiagnosisModalVisible = true;
        }

      });
    },

    async getWesternDiagnosisData(type) {
      if (!this.preVerificationUserMedical()) return;

      await withLoading(this, '数据加载中...')(async () => {
        this.westernDiagnosisTableData = []
        const [icdList, diagnoses] = await Promise.all([
          getDocticdList({pageSize: 100}),
          getReceptionDiagnosis({
            category: 1,
            seeDoctorId: this.patientChooseForm.seeDoctorId
          })
        ]);

        // 3. 处理数据
        this.westernSelectedTable = diagnoses.map(item => ({
          ...item,
          id: item.id,
          chsName: item.insuranceName,
          chsCode: item.insuranceCode,
          code: item.icdCode,
          name: item.diagnosticName,
          remarks: item.remark,
          definiteDiagnosis: parseInt(item.definiteDiagnosis)
        }));

        this.westernDiagnosisTableData = icdList.data;

        // 4. 条件性显示弹窗
        if (type !== 2) {
          this.$nextTick(() => {
            if (this.$refs.westernTable) {
              this.$refs.westernTable.doLayout();
            }
            this.$forceUpdate();
          });
          this.westernDiagnosisModalVisible = true;
        }

      });
    },

    async handleShowDoctordisposeTabel1() {
      if (this.patientForm.syspre === null) {
        this.$message.warning("请录入血压")
        this.$nextTick(() => {
          this.$refs.syspreRef?.focus();
        });
        return;
      }
      if (this.patientForm.ageYear >= 35 && !this.patientForm.bloodNumber) {
        this.$message.warning("年龄 ≥35 岁，必须填写血糖值！");
        this.$nextTick(() => {
          this.$refs.bloodSugarRef?.focus();
        });
        return;
      }
      await withLoading(this, '数据加载中...')(async () => {
        if (!this.patientForm || !this.patientForm.id) return this.$message.warning("请选择患者后进行操作");
        this.doctordisposeTableData = [];
        this.selDoctordisposeDialog = true;
      });
    },

    /*过敏原下拉框*/
    async getAiseList() {
      const res = await getAiseList();
      this.aiseListOptions = res.data.map(item => {
        return {label: item.name, id: item.id}
      })
    },

    /*判断身份证重复和正则验证*/
    async certnoMonitor() {
      if (!this.patientForm.certno) return;

      const certType = this.patientForm.identityCard; // 当前选择的证件类型
      const certLength = this.certLengthMap[certType]; // 获取对应长度要求
      const certPattern = this.certPatterns[certType]; // 获取对应正则规则

      // 长度验证
      if (this.patientForm.certno.length !== certLength) {
        this.$message.error(`请输入${certLength}位证件号码`);
        return;
      }

      // 格式验证
      if (certPattern && !certPattern.test(this.patientForm.certno)) {
        this.$message.error('证件号码格式不正确');
        return;
      }

      // 特殊证件处理（仅身份证需要解析信息）
      if (certType === 1) { // 居民身份证
        console.log(this.patientForm.certno, 'this.patientForm.certnothis.patientForm.certno')
        const res = await getDoesItExistSFZ({certNo: this.patientForm.certno.toString()});
        if (res.data && this.patientForm.certno !== this.patientChooseForm.certno) {
          this.$message.error("该身份证在信息库中已经存在!")
          return 1;
        }
        const genderDigit = parseInt(this.patientForm.certno.charAt(16), 10);
        this.patientForm.sex = genderDigit % 2 === 1 ? '1' : '2';

        // 计算年龄和出生日期
        const data = this.getAgeAndMonthsFromIdCard(this.patientForm.certno);
        this.patientForm.ageYear = data.years;
        this.patientForm.ageMonth = data.months;
        this.patientForm.brdy =
            this.patientForm.certno.slice(6, 10) + '-' +
            this.patientForm.certno.slice(10, 12) + '-' +
            this.patientForm.certno.slice(12, 14);
      } else if (certType === '8') { // 武警身份证件
        // 可选:添加武警证件特殊处理逻辑
        this.patientForm.sex = ''; // 清除非身份证的性别信息
      } else {
        // 其他证件类型清空自动计算字段
        this.patientForm.sex = '';
        this.patientForm.ageYear = '';
        this.patientForm.ageMonth = '';
        this.patientForm.brdy = '';
      }
    },

    /*计算年龄和出生日期*/
    getAgeAndMonthsFromIdCard(idCard) {
      if (!idCard || idCard.length !== 18) return {years: 0, months: 0, birthday: ''};

      const birthStr = idCard.slice(6, 14); // 格式:YYYYMMDD
      const birthday = `${birthStr.slice(0, 4)}-${birthStr.slice(4, 6)}-${birthStr.slice(6, 8)}`;

      const birthDate = new Date(birthday);
      if (isNaN(birthDate.getTime())) return {
        years: 0,
        months: 0,
        birthday: ''
      };

      // 2. 获取当前日期
      const today = new Date();

      // 3. 计算周岁
      let years = today.getFullYear() - birthDate.getFullYear();

      // 4. 计算月龄（总月数差）
      let months = (today.getFullYear() - birthDate.getFullYear()) * 12 +
          (today.getMonth() - birthDate.getMonth());

      // 5. 调整年龄和月龄（如果生日未到）
      if (
          today.getMonth() < birthDate.getMonth() ||
          (today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())
      ) {
        years--;
        months--;
      }

      // 6. 确保月龄为正数
      months = Math.max(0, months % 12); // 超过12个月的部分已计入周岁

      return {years, months, birthday};
    },
    /*一周内就诊数据*/
    async handleSavenData() {
      await withLoading(this, '数据处理中...')(async () => {
        const res = await getFinishReception({
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          startTime: this.seedoctorQueryParams.startTime,
          endTime: this.seedoctorQueryParams.endTime,
          doctorId: this.seedoctorQueryParams.doctorId ?? null,
          patientId: this.seedoctorQueryParams.patientId,
          patientName: this.seedoctorQueryParams.patientName
        });
        this.sevenDayTableData = res.data.content
        this.totalSize = res.data.totalSize;
        this.sevenDayDialogVisible = true;
      });
    },

    /*外层保存患者信息及就诊信息*/
    async handleEditDocphr() {
      await withLoading(this, '数据处理中...')(async () => {
        const valid = await this.$refs.patientFormDataRef.validate();
        if (!valid) {
          this.$message.warning('请检查表单填写是否正确');
          return;
        }
        const isSpecialCase = this.patientForm.thrNot === 1 || this.patientForm.ageYear < 18;
        if (!isSpecialCase) {
          if (!this.patientForm.syspre && !this.patientForm.diapre) {
            this.$message.warning('请填写血压值');
            return;
          }
          if (!this.patientForm.bloodNumber && this.patientForm.ageYear >= 35) {
            this.$message.warning('请填写血糖值');
            return;
          }
        }


        await withLoading(this, '数据提交中...')(async () => {
          // ================= 2. 数据处理 =================
          this.patientForm.conerAddCode =
              this.patientForm.conerAddCodeArr?.length > 0
                  ? this.patientForm.conerAddCodeArr[this.patientForm.conerAddCodeArr.length - 1]
                  : '';
          // ================= 3. 提交第一组数据 =================
          const res = await editDocphr(this.patientForm);
          if (res.code !== 200) {
            this.$message.error(res.message);
            this.loading = false;
            return;
          }
          console.log(this.patientForm.pregnant, 'this.patientForm.pregnantthis.patientForm.pregnant')
          // ================= 4. 准备第二组数据 =================
          const newItem = {
            id: this.patientChooseForm.seeDoctorId,
            address: this.patientForm.conerAddName,
            sex: this.patientForm.sex,
            age: this.patientForm.ageYear,
            allergen: this.patientForm.aiseId,
            bloodType: this.patientForm.bloodType,
            bloodNumber: parseInt(this.patientForm.bloodNumber),
            cardid: this.patientForm.certno,
            doctorId: this.userInfo.staffId,
            patientId: this.patientForm.id,
            patientName: this.patientForm.name,
            patientTell: this.addSeedoctorForm.patientTell,
            nowHistory: this.addSeedoctorForm.nowHistory,
            beforeHistory: this.addSeedoctorForm.beforeHistory,
            diapre: this.patientForm.diapre,
            syspre: this.patientForm.syspre,
            prhCostType: this.patientForm.prhCostType,
            pregnant: this.patientForm.pregnant ? 1 : 0
          };

          console.log(newItem, '就诊信息数据');

          // ================= 5. 提交第二组数据 =================
          const res2 = await editReception(newItem);
          if (res2.code !== 200) {
            this.$message.error(res2.message);
            this.loading = false;
            return;
          }

          // ================= 6. 成功处理 =================
          setTimeout(async () => {
            this.patientChooseForm = {
              ...this.addSeedoctorForm,
              ...this.patientChooseForm,
              ...this.patientForm,
              id: this.patientChooseForm.seeDoctorId,
              allergen: this.patientForm.aiseId,
            };
            this.patientForm = Object.assign({}, this.$options.data.call(this).patientForm);
            await this.handleClickReceptionRow(this.patientChooseForm,1);
            await this.loadAndDisplayAddress();
          });
        }, 1000);

      });
    },
    /*挂号类别下拉框*/
    async getRegisterType() {
      if (this.registerOptions.length > 0) return;
      const res = await getRegisterType({doctorId: this.userInfo.staffId});
      this.registerOptions = res.data.map(item => {
        return {label: item.designation, id: item.id, odcost: item.odcost, mainType: item.mainType}
      })
    },
    /*医生下拉框*/
    async getDoctorList() {
      if (this.doctorOptions.length > 0) return;
      const res = await getDoctorList()
      this.doctorOptions = res.data.map(item => {
        return {id: item.id, label: item.fullName}
      })
    },
    /*科室下拉框*/
    async getDeptList() {
      if (this.deptOptions.length > 0) return;
      const res = await getDeptList();
      this.deptOptions = res.data.map(item => {
        return {id: item.id, label: item.deptName}
      })
    },
    /*模板新增修改名称转拼音*/
    handleNameChangeCode(v, i) {
      switch (i) {
        case 1:
          this.templateForm.pinyin =
              pinyin(this.templateForm.name, {pattern: 'first', toneType: 'none', separator: ''}).toLocaleUpperCase();
          this.addUnitForm.pyCode =
              pinyin(this.addUnitForm.name, {pattern: 'first', toneType: 'none', separator: ''}).toLocaleUpperCase();
          break;
        case 2:
          this.aiseForm.pyCode =
              pinyin(this.aiseForm.name, {pattern: 'first', toneType: 'none', separator: ''}).toLocaleUpperCase();
          break;
      }
    },
    /*新增修改合约单位*/
    async handleAddContractUnit() {
      await withLoading(this, '数据提交中...')(async () => {
        if (this.addUnitForm.id) {
          const res = await editContractUnit(this.addUnitForm);
          if (res.code === 200) {
            await this.getContuntList();
            this.addUnitModalVisible = false;
          } else {

            this.$message.error(res.message)
          }
        } else {
          const res = await addContractUnit(this.addUnitForm);
          if (res.code === 200) {
            await this.getContuntList();
            this.addUnitModalVisible = false;
          } else {
            this.$message.error(res.message)
          }
        }
        this.addUnitForm = Object.assign({}, this.$options.data.call(this).addUnitForm)

      });
    },
    /*关闭快速就诊模态框*/
    handleCancelContract() {
      const initialData = this.$options.data.call(this);
      this.patientForm = Object.assign({}, initialData.patientForm);
      this.conerPleasett = '';
      this.receptionForm = Object.assign({}, initialData.receptionForm || {});
      this.templateForm = Object.assign({}, initialData.templateForm || {});
      this.addSeedoctorForm = Object.assign({}, initialData.addSeedoctorForm || {});
      this.patientChooseForm = Object.assign({}, initialData.patientChooseForm || {});
      this.templateFormRef = Object.assign({}, initialData.templateFormRef || {});
      this.medicalAdviceData = [];
      if (this.$refs.templateFormRef) this.$refs.templateFormRef.clearValidate();
      this.isInputDisabled = false;
      this.receptionModalVisible = false;
      this.tpAddOrEditMedicineDialog = false;
    },
    /*关闭新增修改模板模态框*/
    handleCancelTemplateForm() {
      this.templateForm = Object.assign({}, this.$options.data.call(this).templateForm)
      this.tpAddOrEditMedicineDialog = false;
    },
    /*重置表单*/
    handleResetContract() {
      const initialData = this.$options.data.call(this);
      this.patientForm = Object.assign({}, initialData.patientForm);
      this.templateForm = Object.assign({}, initialData.templateForm || {});
      this.addSeedoctorForm = Object.assign({}, initialData.addSeedoctorForm || {});
      this.fastReceptionForm = Object.assign({}, initialData.fastReceptionForm || {});
      this.patientChooseForm = Object.assign({}, initialData.patientChooseForm || {});
      this.conerPleasett = '';
      this.naplPleasett = '';
      this.medicalAdviceData = [];
      this.isInputDisabled = false;
    },
    /*修改合约单位*/
    async handleEditContractUnit(item) {
      const res = await getContractUnit(item.id.toString())
      this.addUnitForm = res.data
      this.addUnitModalVisible = true;
    },
    /*新增合约单位*/
    handleSaveContractUnit() {
      this.$closeAllSelects();
      this.addUnitForm = Object.assign({}, this.$options.data.call(this).addUnitForm)
      this.addUnitModalVisible = true;
    },

    handleAddOrEditAise() {
      if (!this.aiseForm.id) {
        this.aiseAddRrEditTtiel = '新增过敏原'
      } else {
        this.aiseAddRrEditTtiel = '编辑过敏原'
      }
      this.$closeAllSelects();
      this.aiseForm = Object.assign({}, this.$options.data.call(this).aiseForm)
      this.aiseAddOrEditMedicineDialog = true;
    },
    /*就诊列表但单击行事件*/
    async handleClickRow(row) {
      this.patientChooseForm = JSON.parse(JSON.stringify(row));
    },
    /*选择患者或切换患者组装数据*/
    async handleClickReceptionRow(row, skip) {
      // 1. Check for unsaved changes
      if (skip !== 1 && this.patientForm.name &&
          !await this.$confirm('患者信息可能未保存，确认切换患者吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(() => false)) return;

      await withLoading(this, '加载患者信息中...')(async () => {
        // 2. Parallel data fetching with optimized requests
        this.medicineSearchQuery =  '';
        const [patientInfo,patientData] = await Promise.all([
          getDocphrList(row.patientId),
          getPatientAllData({id:row.id}),
        ]);
        console.log(patientData,'patientDatapatientDatapatientData')

        // 3. Pre-process data for better performance
        const seeDoctorDataObj = patientData.data.cncSeeDoctorRespVO;
        const advicesData = patientData.data.dugDoctorAdviceRespVOList;
        const results = ['未知', '阴性', '阳性'];
        // 4. Process medical advice data with optimized methods
        this.medicalAdviceData = advicesData.map(item => {
          if ([0, 1, 6].includes(item.orderType)) {
            const processed = item.content
                .replace(/\/n/g, ' ')
                .split(' ')
                .filter(Boolean)
                .map(s => s.trim());

            if (item.orderType === 1 || item.orderType === 6) {
              item.content = processed.flatMap(s => s.split(',').filter(Boolean).map(i => i.trim())).join(' ');
            } else {
              item.content = processed.join(' ');
            }
          }

          if (item.skintstDicm === 1) {
            item.content += `\n(皮试结果:${results[item.skintstDicmResult] || '未知'})`
          }
          return item;
        });

        // 5. Set form data with optimized operations
        this.doctordisposeTableData = patientData.data.cncDoctorDisposeRespVOList;

        const westPrescriptions = [];
        const chinaPrescriptions = [];
        advicesData.forEach(a => {
          if (a.orderType === 0) {
            westPrescriptions.push(a.content.replace(/\s+/g, ' ').trim());
          } else if (a.orderType === 1) {
            chinaPrescriptions.push(a.content.replace(/,/g, ' '));
          }
        });

        this.addSeedoctorForm = {
          ...this.addSeedoctorForm,
          westernDiagnos: patientData.data.cncDiagnosisRespVOList.filter(item => item.diagnosticCategory === '1').map(d => `(${d.diagnosticName})`).join(''),
          chinaDiagnose: patientData.data.cncDiagnosisRespVOList.filter(item => item.diagnosticCategory === '2').map(d => `(${d.diagnosticName})`).join(''),
          westchinaPrescription: westPrescriptions.join(' '),
          chinaPrescription: chinaPrescriptions.join(' '),
          patientTell: seeDoctorDataObj.patientTell,
          nowHistory: seeDoctorDataObj.nowHistory,
          beforeHistory: seeDoctorDataObj.beforeHistory,
        };

        this.patientChooseForm = {
          ...patientInfo.data,
          seeDoctorId: row.id,
          patientId: row.patientId,
          dregisterTableId: row.dregisterTableId,
          repeated: row.seeCount > 1 ? 1 : 2,
          bloodNumber: seeDoctorDataObj.bloodNumber,
          bloodType: seeDoctorDataObj.bloodType,
          syspre: seeDoctorDataObj.syspre,
          diapre: seeDoctorDataObj.diapre,
          aiseId: seeDoctorDataObj.allergen ? parseInt(row.allergen) : null,
          pregnant: row.pregnant,
        };

        await this.handleChoosePatient();
        const res = await getMedicineCache({seeDoctorId:row.id});
        const parsedData = JSON.parse(res.data);

        // 处理west数据
        if (parsedData?.west && skip !== 1) {
          const westArray = JSON.parse(parsedData.west);
          if (Array.isArray(westArray)) {
            this.westMedicineTableData.push(...westArray);
          }
        }

        // 处理china数据
        if (parsedData?.china && skip !== 1) {
          const chinaArray = JSON.parse(parsedData.china);
          if (Array.isArray(chinaArray)) {
            this.chinaMedicineTableData.push(...chinaArray);
          }
        }
      });
    },
    /*组装患者数据*/
    async handleChoosePatient() {
      await withLoading(this, '数据处理中...')(async () => {
        // 1. 预处理身份证信息
        const ageData = (() => {
          const certno = this.patientChooseForm.certno?.trim();
          if (!certno) return { ageYear: null, ageMonth: null, brdy: null };

          try {
            const ageInfo = this.getAgeAndMonthsFromIdCard(certno);
            return {
              ageYear: ageInfo.years,
              ageMonth: ageInfo.months,
              brdy: ageInfo.birthday
            };
          } catch (error) {
            console.error('身份证解析错误:', error);
            return { ageYear: null, ageMonth: null, brdy: null };
          }
        })();

        // 2. 直接赋值基础信息，减少中间对象创建
        const form = this.patientForm;
        const chooseForm = this.patientChooseForm;
        const matchedUnit = this.contractUnitOption.find(item => item.id === chooseForm.phrUnt);

        form.id = chooseForm.id || null;
        form.patId = chooseForm.patId || null;
        form.patientId = chooseForm.patientId || null;
        form.dregisterTableId = chooseForm.dregisterTableId || null;
        form.repeated = chooseForm.repeated || null;
        form.name = chooseForm.name || null;
        form.sex = chooseForm.sex ? chooseForm.sex.toString() : null;
        form.certno = chooseForm.certno || null;
        form.identityCard = chooseForm.identityCard || 1;
        form.naty = chooseForm.naty || 3;
        form.jobId = chooseForm.jobId || null;
        form.ntlyId = parseInt(chooseForm.ntlyId) || null;
        form.phrUnt = matchedUnit ? chooseForm.phrUnt : null;
        form.mrgState = chooseForm.mrgState || null;
        form.tel = chooseForm.tel || null;
        form.conerName = chooseForm.conerName || null;
        form.conerTel = chooseForm.conerTel || null;
        form.conerRltsId = chooseForm.conerRltsId || null;
        form.prhCostType = chooseForm.prhCostType || null;
        form.prhType = chooseForm.prhType || null;
        form.aiseId = chooseForm.aiseId || null;
        form.bloodNumber = chooseForm.bloodNumber || null;
        form.bloodType = chooseForm.bloodType || '1';
        form.syspre = chooseForm.syspre || null;
        form.diapre = chooseForm.diapre || null;
        form.pregnant = chooseForm.pregnant === 1;
        form.seedoctorcCount = null;
        form.seedoctorcType = null;
        form.naplAddName = chooseForm.naplAddName || null;
        form.conerAddName = chooseForm.conerAddName || null;
        form.ageYear = ageData.ageYear || null;
        form.ageMonth = ageData.ageMonth || null;
        form.brdy = ageData.brdy || null;

        // 3. 优化行政区划处理
        const processRegion = (code, arrName) => {
          const codeStr = code?.toString().trim();
          if (!codeStr) return;

          form[arrName] = [
            this.formatRegionCode(codeStr, 2, 10),
            this.formatRegionCode(codeStr, 4, 8),
            this.formatRegionCode(codeStr, 6, 6),
            this.formatRegionCode(codeStr, 9, 3),
            codeStr
          ];
        };

        form.naplAddCodeArr = [];
        form.conerAddCodeArr = [];
        processRegion(chooseForm.naplAddCode, 'naplAddCodeArr');
        processRegion(chooseForm.conerAddCode, 'conerAddCodeArr');

        // 4. 并行加载地址信息
        await Promise.all([
          form.conerAddCodeArr.length > 0 ? this.loadAndDisplayAddress('coner') : Promise.resolve(),
          form.naplAddCodeArr.length > 0 ? this.loadAndDisplayAddress('napl') : Promise.resolve()
        ]);

        this.isFormExpanded = !!this.isFormExpanded;
        this.patientDialogVisible = false;
      });
    },
    /*数据字典*/
    async dict() {
      try {
        // 重命名API调用避免函数名冲突
        const res = await dict();
        const {data} = res;

        // 映射配置：统一管理所有选项的转换规则
        const optionMappings = [
          {key: 'nationOption', path: 'natyEntities'},
          {key: 'certypeOption', path: 'certypeEntities'},
          {key: 'jobOption', path: 'jobEntities'},
          {key: 'profttlOption', path: 'profttlEntities'},
          {key: 'prhCostOption', path: 'prhCostType'},
          {key: 'prhTypeOption', path: 'prhType'},
          {key: 'rltsEntitiesOption', path: 'rltsEntities'},
          {key: 'untAtteOption', path: 'unatteVo'},
          {key: 'ntlyOptions', path: 'country'},
          {key: 'chinaMakeOptions', path: 'methodTypeVO'},
          {key: 'tcmwayOptions', path: 'tcmway'},
          {key: 'mrgStateOptions', path: 'mrgStateEntities'},
          {key: 'rxTypeOptions', path: 'rxTypeVOS'}
        ];

        // 批量处理标准映射（id + label）
        optionMappings.forEach(({key, path}) => {
          this[key] = (data[path] || []).map(item => (
              {id: item.id, label: item.name}
          ));
        });

        // 特殊处理：包含额外字段的映射
        this.medicationWayOptions = (data.ruteVo || []).map(item => (
            {
              id: item.id,
              label: item.name,
              type: item.type,
              exeB: item.exeB,
              lmtSpc: item.lmtSpc
            }
        ));
      } catch (error) {
        console.error('字典数据加载失败:', error);
        this.$message.error('系统字典初始化失败，请刷新页面重试');
      }
    },
    /*往来单位列表*/
    async getContuntList() {
      if (this.contractUnitOption.length > 0) return;
      const res = await getContuntList({state: 1});
      this.contractUnitOption = res.data.map(item => {
        return {id: item.id, label: item.name, code: item.code}
      })
    },
    /*数据源*/
    async loadData() {
      const today = new Date();
      const formattedDate = today.toISOString().split('T')[0];
      const res1 = await getDeptInDoctorList({
        date: formattedDate,
        depId: this.userInfo.selDept,
        doctorId: this.userInfo.staffId,
        visitState: 2
      });
      const res2 = await getReceptionList({doctorId: this.userInfo.staffId, status: 1});
      this.tableData1 = res1.data;
      this.tableData2 = res2.data;
      const sortedData = [...this.tableData1]?.sort((a, b) => {
        return new Date(a.regTime) - new Date(b.regTime);
      });
      sortedData?.map((item, index) => {
        item.optTime = item.optTime.substring(5);
        item.regDeptName = this.deptOptions?.find(dept => dept.id === item.regDepId)?.label ?? '';
        item.order = index + 1;
      })

    },
    /*魔法数字对应数组回显*/
    safeGetMappedValue(col, row, type) {

      const hiddenProps = new Set([
        'usedfrquId', 'sdoseCnt', 'prdCnt', 'prdDays', 'medcWayId', 'tcmCnt',
        'selfProe', 'skintstRslt', 'remark', 'remarks', 'rxDosCnt',
      ]);

      if (hiddenProps.has(col.prop)) {
        return ''; // 直接返回空字符串，不显示
      }
      // 1. 检查数据有效性
      const rawValue = row[col.prop];
      if (rawValue === null || rawValue === undefined) return ' ';

      // 2. 检查映射数组
      const mapArray = this[col.op];
      if (!col.op || !Array.isArray(mapArray)) return rawValue;

      // 3. 执行映射
      const matched = mapArray.find(item => item.id == rawValue);
      return matched?.label || rawValue;
    },
    /*行政划分码补0辅助方法*/
    formatRegionCode(code, prefixLength, zeroPadding) {
      if (!code || code.length < prefixLength) {
        return code || '';
      }
      return code.substring(0, prefixLength) + '0'.repeat(zeroPadding);
    },
    /*自动计算列宽*/
    getColumnWidth(label, prop, tableData) {
      const minWidth = 100;
      const padding = 30;
      const contentList = tableData.map(item => item?.[prop] ?? '');
      const widths = [...contentList, label].map(text => {
        const str = String(text || '');
        return this.getTextWidth(str) + padding;
      });

      return Math.max(minWidth, ...widths);
    },
    /*自动计算列宽辅助方法*/
    getTextWidth(text, fontSize = 14) {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      ctx.font = `${fontSize}px Microsoft YaHei`;
      return ctx.measureText(text).width;
    },
    /*列头剧中*/
    labelHead(h, {column, $index}) {
      let l = column.label.length;
      let f = 12;
      column.minWidth = f * (l + 5); //加上一个文字长度
      return h("div", {class: "table-head", style: {width: "100%"}}, [
        column.label,
      ]);
    },

    handleSizeChange(val) {
      this.pageNum = val;
      this.handleSavenData();
    },
    //当前条数改变触发
    handleCurrentChange(val) {
      this.pageNum = val;
      this.handleSavenData();
    },
  }
}
</script>

<style lang="less" scoped>
.hidden-dialog {
  visibility: hidden;
  /* 如果不想占用布局空间，可以加上： */
  position: absolute;
}
.blood-pressure-error .el-input__inner {
  border-color: red;
  color: red;
}
/* 滚动条统一样式 */
:root {
  scrollbar-width: thin !important;
  scrollbar-color: #c0c4cc #f5f7fa !important;
}

:deep(.el-table__body-wrapper) {
  overflow-x: auto;
  overflow-y: auto;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 0;
  height: 8px;
}

:deep(::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(::-webkit-scrollbar-thumb) {
  background: #c0c4cc;
  border-radius: 10px;
  height: 20px;
}

:deep(::-webkit-scrollbar-track) {
  background: #f5f7fa;
  border-radius: 10px;
}

/* 基础布局 */
.modern-sidebar {
  border-radius: 12px 0 0 12px; /* 修改：左上角和左下角12px圆角，右上角和右下角直角 */
  height: 100%;
  display: flex;
  flex-direction: column;
}

.sidebar-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 表格容器 */
.waiting-table, .reception-table {
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.waiting-table {
  flex: 0 0 40%;
}

.reception-table {
  flex: 1;
  position: relative;
}

/* 表格样式 */
.sticky-header-table {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border-radius: 0 0 4px 4px;
}

.sticky-header-table :deep(.el-table__header-wrapper) {
  position: sticky;
  top: 0;
  z-index: 10;
  background: white;
}

.sticky-header-table :deep(.el-table__body-wrapper) {
  flex: 1;
  overflow: auto;
}

/* 现代风格搜索输入框 */
.modern-search-input {
  width: 500px;
}

.modern-search-input /deep/ .el-input__inner {
  height: 36px;
  line-height: 36px;
  padding-left: 35px;
  border-radius: 18px;
  border: 1px solid #DCDFE6;
}

.modern-search-input /deep/ .el-input__prefix {
  font-size: 20px; /* 调整图标大小 */
  margin-top: -3px;
}


/* 确保表格容器正确计算宽度 */
.disabled-table .el-table__body-wrapper {
  overflow-x: auto !important;
}

/* 强制表格布局模式 */
.el-table {
  display: table !important;
  table-layout: fixed !important; /* 关键：固定布局 */
}

/* 修正固定列的层级 */
.el-table__fixed-right {
  height: 100% !important; /* 避免固定列高度溢出 */
}

.audio-player {
  margin-right: 20px;
}

/* 适配紧凑布局 */
.el-header {
  padding: 0 20px !important;
}

/* 音频控件样式优化 */
audio {
  outline: none;
  border-radius: 4px;
}

.audio-placeholder {
  line-height: 60px;
  color: #909399;
}

.recording-status {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  text-align: center;
}

.wave-animation {
  width: 100px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.wave-animation::before, .wave-animation::after, .wave-animation span {
  content: '';
  width: 10px;
  height: 100%;
  background: #f56c6c;
  border-radius: 5px;
  animation: wave 1s ease-in-out infinite;
}

.wave-animation::before {
  animation-delay: 0s;
}

.wave-animation span {
  animation-delay: 0.2s;
}

.wave-animation::after {
  animation-delay: 0.4s;
}

@keyframes wave {
  0%, 100% {
    transform: scaleY(0.3);
  }
  50% {
    transform: scaleY(1);
  }
}

::v-deep .el-table .row-positive {
  background-color: #f1b0b9 !important;
}

::v-deep .el-table .row-negative {
  background-color: #bcfd76 !important;
}

.disabled-table {
  opacity: 0.6;
}

.disabled-table .el-table__body-wrapper * {
  pointer-events: none;
  cursor: not-allowed;
}

/* 允许滚动条交互 */
.disabled-table .el-table__body-wrapper {
  pointer-events: auto !important;
}

::v-deep .el-table .warning-row {
  background-color: #ff0000 !important;

  td {
    background-color: transparent !important;
  }

  &:hover td {
    background-color: #ff0000 !important;
  }
}

/* 深度覆盖Element UI默认样式 */
.compact-mini-table {
  font-size: 13px !important; /* 缩小字体 */
}

.compact-mini-table .el-table__header th,
.compact-mini-table .el-table__body td {
  padding: 4px 0 !important; /* 减少单元格内边距 */
  line-height: 20px !important; /* 行高压缩 */
}

.compact-mini-table .el-table__row {
  height: 28px !important; /* 固定行高 */
}

/* 缩小复选框 */
.compact-mini-table .el-checkbox__inner {
  width: 14px;
  height: 14px;
}

.compact-cell {
  .cell {
    padding-left: 3px !important;
    padding-right: 3px !important;
  }
}

.compact-content {
  white-space: pre-line;
  text-align: center;
  font-size: 11px; /* 内容区更小字号 */
  line-height: 1.2;
}

.patient-dialog {
  display: flex;
  justify-content: center;
  align-items: Center;
  overflow: auto;

  .el-dialog {
    margin: 0 auto !important;
    position: relative;

    .el-dialog__header {
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      width: 100%;
      height: 60px;
      z-index: 1;
    }

    .el-dialog__body {
      width: 100%;
      overflow: hidden;
      overflow-y: auto;
      max-height: 80vh; //最大高度为视口高度的90%
      padding-top: 80px;
      padding-bottom: 100px;
      z-index: 1;
    }

    .el-dialog__footer {
      position: absolute;
      left: 0;
      bottom: 0;
      right: 0;
      width: 100%;
      height: 80px;
      z-index: 1;
    }
  }
}

/* 容器高度控制链 */
.medical-orders-container {
  flex: 1; /* 关键：占据剩余空间 */
  min-height: 200px; /* 最小高度 */
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止溢出 */
}

.medical-orders-tabs {
  flex: 1; /* 继承父容器高度 */
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止溢出 */
}

/* 标签页内容区域 */
.medical-orders-tabs .el-tabs__content {
  flex: 1; /* 关键：占据剩余空间 */
  overflow: hidden; /* 防止溢出 */
  position: relative; /* 用于定位右键菜单 */
}

/* 表格样式修正 */
.medical-orders-tabs .el-table {
  width: 100%;
  height: 100% !important;
  display: flex;
  flex-direction: column;
}

/* 真正控制滚动的部分 */
.medical-orders-tabs .el-table__body-wrapper {
  flex: 1;
  overflow-y: auto !important;
  overflow-x: hidden !important;
}

/* 表头固定 */
.medical-orders-tabs .el-table__header-wrapper {
  flex-shrink: 0;
}

::v-deep .el-cascader .el-input__inner::placeholder {
  color: var(--el-text-color-placeholder) !important; /* 使用官方变量 */
}

.prescription-button .el-button:hover {
  background-color: #f5f7fa !important;
}

.group-tag {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 6px;
  border-radius: 3px;
}

/* 分组图标（居中显示） */
.group-icon {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 14px;
}

/* 调整第一列内边距 */
.el-table .el-table__cell:first-child {
  padding-left: 30px !important;
}


.compact-form-box,
.el-tab-pane {
  overflow: auto !important;
}

/* 表格布局统一设置 */
.el-table {
  display: flex !important;
  flex-direction: column !important;
}

.el-table__header-wrapper {
  flex: 0 0 auto !important;
}

.el-table__body-wrapper {
  flex: 1 1 auto !important;
  overflow-y: auto !important;
  overflow-x: hidden !important;
}

/* 修复边框显示 */
.el-table--border {
  border-bottom: none;
}

.context-menu {
  position: fixed;
  z-index: 9999;
}

.no-line {
  border-top: none !important;
  padding-top: 0 !important;
}

/* 方法2:使用/deep/的正确姿势 */
.blood-pressure-container /deep/ .blood-pressure-error .el-input__inner {
  color: #f56c6c !important;
}

/* 表单项整体样式 */
.address-form-item {
  .el-form-item__content {
    display: flex;
    width: 100%;
  }
}

/* 统一宽度样式 */
.wide-address-selector,
.wide-address-input {
  width: 500px !important; /* 调整为需要的宽度 */
  min-width: 100%; /* 保证响应式 */

  /* 深度选择器穿透element-ui内部样式 */

  ::v-deep {
    .el-input__inner {
      height: 30px;
      line-height: 40px;
      font-size: 14px;
    }

    /* 级联选择器下拉面板宽度 */

    .el-cascader-menu {
      min-width: 140px;
    }
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .wide-address-selector,
  .wide-address-input {
    width: 100% !important;
  }
}

.form-row {
  margin-bottom: 5px;
}

/* 调整地址选择器的间距 */
.age-input-address > * {
  margin-right: 5px;
}

/* 年龄输入框样式 */
.age-input-group > * {
  margin-right: 5px;
}

/* 紧凑表单样式 */
.compact-form .el-form-item {
  margin-bottom: 12px;
}

.empty-tip {
  width: 100%;
  height: 200px; /* 与min-height保持一致 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.tip-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.tip-content i {
  font-size: 24px;
  margin-bottom: 5px;
  color: #C0C4CC;
}

.highlight {
  background: #1890ff !important; /* 背景蓝色 */
  color: white; /* 文字白色（确保可读性） */
  border-color: #1890ff; /* 可选:边框也变蓝色 */
}

.compact-method-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 确保每排4个 */
  gap: 10px;
  padding: 5px;
}

.compact-method-item {
  padding: 5px;
  text-align: center;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
}

.compact-method-item:hover {
  background-color: #409EFF;
  color: white;
}

/* 按钮区域样式 */
.dialog-footer {
  text-align: right;
  padding: 10px 15px;
  margin-top: 25px;
  padding-right: 15px;
  border-top: 1px solid #e1e4e8;
}

.medicine-whiteboard {
  min-height: 200px;
  border: 2px dashed #DCDFE6;
  border-radius: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin: 10px 0;
  padding: 10px;
}

.medicine-block {
  width: 150px;
  height: 80px;
  border: 1px solid #409EFF;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: space-between; /* 均匀分布三个部分 */
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  padding: 10px 5px; /* 增加内边距 */
}

.medicine-method {
  font-size: 12px;
  color: #909399;
  width: 100%;
  text-align: center;
  margin-bottom: 5px;
  word-break: break-word; /* 长文本换行 */
}

.medicine-name {
  font-size: 16px;
  text-align: center;
  width: 100%;
  margin: auto 0; /* 垂直居中 */
  font-weight: 500;
}

.medicine-dose {
  font-size: 12px;
  color: #909399;
  width: 100%;
  text-align: center;
  margin-top: 5px;
}

.medicine-block:hover {
  box-shadow: 0 2px 12px 0 rgba(64, 158, 255, 0.2);
  transform: translateY(-2px);
}

.add-medicine {
  /* 保持原有添加按钮样式 */
  width: 150px;
  height: 100px;
  border: 1px dashed #DCDFE6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
  cursor: pointer;
}

/* Vue 2样式穿透写法 */
.medicine-dose-input::v-deep .el-input__inner {
  text-align: center;
  padding: 0 5px;
}

.medicine-dose-input::v-deep .el-input-group__append {
  padding: 0 5px;
  background-color: #f5f7fa;
}

/deep/ .el-table__row.red-row .cell {
  color: red !important;
}


.el-input {
  cursor: pointer;
}

/* 表格容器样式 */
.table-container {
  width: 100%; /* 宽度100%适应弹窗 */
}

/* 自定义弹窗样式（全局样式） */
:global(.medicine-popover) {
  padding: 0 !important; /* 去除内边距 */
  max-width: 1000px; /* 最大宽度限制 */
}

/* 表格滚动条相关样式 */
.table-container::-webkit-scrollbar {
  height: 8px; /* 水平滚动条高度 */
  width: 8px; /* 垂直滚动条宽度 */
}

.table-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

/* 确保表格有固定高度和滚动条 */
.fixed-height-table {
  height: 100vh; /* 固定高度 */
  overflow-y: auto; /* 垂直滚动 */
}

/* 确保 el-table 内部正确显示滚动条 */
.fixed-height-table .el-table__body-wrapper {
  overflow-y: auto !important;
}


.context-menu {
  position: fixed;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  z-index: 9999;
  min-width: 60px;
  max-width: 300px;
  padding: 5px 0;
}

.menu-header {
  padding: 5px 12px;
  color: #909399;
  font-size: 12px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 5px;
}

.menu-item {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.menu-item:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

.menu-item i {
  margin-right: 5px;
}

.menu-divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 5px 0;
}

.medical-info-form {
  border-radius: 4px;
  padding: 0 !important;
}

.medical-header {
  font-weight: bold;
  font-size: 15px;
  color: #333;
}


.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.form-item label {
  width: 60px;
  text-align: right;
  padding-right: 8px;
  font-size: 13px;
  color: #666;
}


/* 表格标题容器 - 修改版 */
.table-title-container {
  background-color: #0b5baf;
  border-radius: 5px;
  position: relative;
}

.quick-consult-btn {
  background-color: #1a7cff;
  border-color: #1a7cff;
  color: white;
  margin-left: auto; /* 关键:将按钮推到最右侧 */
  margin-right: 30px; /* 关键:将按钮推到最右侧 */
}


/* 标题内容包装 - 修改版 */
.table-title-wrapper {
  padding: 8px 16px; /* 适当内边距 */
  display: flex;
  align-items: center;
  width: 100%;
}

/* 标题文本 */
.title-text {
  font-size: 14px;
  font-weight: bold;
  color: white; /* 白色文字 */
}

/* 病人数量 */
.patient-count {
  margin-left: 8px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8); /* 半透明白色 */
}

/* 调整表格区域间距 */
.table-area {
  margin-top: 0; /* 去除顶部间距 */
  margin-bottom: 16px;
}

/* 确保表格无边框间距 */
.first-table, .second-table {
  border-top: none;
}

.main-container {
  height: 100%;
  width: 100vw;
  max-width: 100vw; /* 确保不超过视口宽度 */
  overflow: auto;
  position: relative;
  box-sizing: border-box; /* 包含padding和border */
  padding: 0 10px; /* 左右留白防止内容贴边 */
}

/* 修复Element UI表格的滚动问题 */
.main-container .el-table__body-wrapper {
  flex: 1;
  overflow: auto;
}

/* 修复flex布局的列溢出问题 */
.main-container .el-col {
  min-width: 0; /* 重要:允许列内容收缩 */
}

/* 主容器滚动条样式 */
.main-container::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.main-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.main-container .el-table {
  width: 100% !important;
  display: flex !important;
  flex-direction: column;
}

.left-col {
  z-index: 100;
  height: 100%;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #ebeef5;
}


.right-col {
  height: 100%;
  width: 80vw;
  padding: 8px;
  background: #f5f7fa;
}

.table-area {
  height: 100%;
  padding: 1px;
}

.form-container {
  height: 100%;
}

.el-table {
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}

.el-form-item {
  margin-bottom: 18px;
}

/*=========================================================*/

.celerity-filing-button {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px; /* 增加与表单的距离 */
}

/deep/ .el-dialog__header {
  padding: 18px;
  background-color: #007bb0;
}

/deep/ .el-dialog__title {
  font-size: 18px;
  color: #fff;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

/deep/ .el-input.is-disabled .el-input__inner {
  color: #87898f;
}

/deep/ .el-textarea.is-disabled .el-textarea__inner {
  color: #87898f;
}

.dialog {
  .addUnitDialog {
    .tabs {
      /deep/ .el-select > .el-input {
        width: 172px;
      }

      /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 172px;
      }

      /deep/ .el-form-item__content {
        display: flex;

        span {
          font-size: 12px;
        }
      }

      .oneLine {
        width: 524px;
        // background-color: indianred;
      }
    }

    /deep/ .el-dialog__title {
      font-size: 15px;
    }

    /deep/ .el-table {
      font-size: 15px;
    }
  }
}

.custom-dialog-footer {
  display: flex;
  justify-content: space-between; /* 左右两侧分开 */
  align-items: center; /* 垂直居中 */
  margin-top: 10px;
}

.left-buttons,
.right-buttons {
  display: flex;
  gap: 10px; /* 按钮间距 */
}

/* 如果需要右侧按钮组靠右对齐 */
.right-buttons {
  margin-left: 100px;
}


.auto-height-button {
  height: 100% !important; /* 继承父容器高度 */
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 0 4px 4px 0 !important; /* 保持圆角匹配 */
}

/* 确保输入框和按钮高度统一 */
.input-with-button .el-input__inner {
  height: 40px; /* 调整这个值会同时改变按钮高度 */
}

.main {
  height: 480px; /* 改为自适应高度 */
  padding: 0 6px; /* 调整内边距 */
  width: 100%;
  display: flex;
  justify-content: space-between;
}

/* 侧边面板样式 */
.side-panel {
  width: 240px;
  padding: 10px;
  background: #f5f7fa;
}

/* 右侧挂号盒子（固定宽度+贴顶） */
.registration-box {
  width: 170px;
  background: white;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  align-self: flex-start; /* 顶部对齐 */
  margin: 0 8px 0 0;
}

/* 数据行样式 */
.data-row {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}

.label {
  width: 70px;
  font-size: 13px;
}

.el-input {
  flex: 1;
}

.label {
  width: 70px;
  font-size: 13px;
  color: #666;
  margin-right: 4px;
}

.el-input {
  flex: 1;
}

.el-input.is-disabled .el-input__inner {
  background-color: #f5f5f5;
  color: #666;
}

/* 新增样式 */
.register-group {
  width: 50%;
  display: flex;
  gap: 16px;
  margin-top: 8px;
}


/* 强制同行显示 */
.register-type + .clinic-room {
  margin-left: -8px; /* 补偿间距 */
}

/* 关键修复样式 */
.compact-form {
  /* 在原有样式基础上添加 */

  .register-type,
  .clinic-room {
    flex: 1; /* 平分剩余空间 */
    min-width: 240px; /* 最小宽度保证换行后对齐 */
    max-width: 50%; /* 最大不超过50% */

    /deep/ .el-form-item__content {
      width: calc(100% - 90px) !important; /* 匹配label宽度 */
    }
  }

  /* 强制同行显示 */

  .register-type + .clinic-room {
    margin-left: -8px; /* 补偿间距 */
  }

  /deep/ .el-form-item__content {
    margin-left: 0 !important; /* 消除ElementUI默认的左侧间距 */
    width: auto !important; /* 取消固定宽度 */
  }

  /deep/ .el-form-item__label {
    padding-right: 6px !important; /* 标签与输入框间距 */
    width: auto !important; /* 取消标签固定宽度 */
    flex: none !important; /* 禁用flex自动分配 */
  }

  .el-form-item {
    /* 调整整体间距 */
    gap: 4px; /* 标签与控件间距 */

    /* 微调对齐方式 */
    align-items: baseline;
  }

  /* 特殊处理复选框 */

  .el-checkbox {
    margin-left: 2px;

    /deep/ .el-checkbox__label {
      display: none; /* 隐藏默认标签 */
    }
  }

  /* 输入框尺寸补偿 */

  .el-input--mini {
    line-height: 28px;

    /deep/ .el-input__inner {
      padding: 0 8px;
    }
  }
}

.compact-form-box {
  height: 100%;
  padding: 20px 8px;
}

.compact-form {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 16px; /* 行列间距 */

  .el-form-item {
    margin: 0;
    display: inline-flex;
    align-items: center;

    /* 标签对齐 */

    /deep/ .el-form-item__label {
      line-height: 28px;
      padding-right: 4px;
    }

    /* 表单控件通用样式 */

    .el-input,
    .el-select,
    .el-date-editor {
      width: 100px; /* 默认宽度 */
    }

    /* 特定字段宽度调整 */

    &[label="性别:"] .el-select {
      width: 70px;
    }


    &[label="职业:"] .el-select {
      width: 130px;
    }

    &[label="病员费别:"] .el-select,
    &[label="病员类型:"] .el-select {
      width: 135px;
    }

    &[label="联系电话:"] .el-input {
      width: 135px;
    }


    &[label="挂号类别:"] .el-select,
    &[label="诊室:"] .el-select {
      width: 300px;
    }

    /* 年龄输入组 */

    .age-input-group {
      display: flex;
      align-items: center;

      .el-input {
        width: 32px !important;

        & + .age-unit {
          margin: 0 2px;
        }
      }
    }

    /* 地址输入组 */

    .age-select-address {
      display: flex;
      align-items: center;
      gap: 4px;

      .el-input {
        width: 60px !important;

        &:nth-last-child(2) {
          width: 150px !important;
        }

        /* 乡镇输入框 */
      }
    }
  }

  /* 分隔线样式 */

  .divider-line {
    width: 100%;
    margin: 5px 10px 0;
    border-top: 1px solid #ebeef5;
  }
}


.compact-form-box {
  border-radius: 4px;
  padding: 12px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: height 0.3s ease;
  overflow: auto;
  border: 1px solid #ebeef5;
  height: auto !important; /* 强制生效 */
}

.compact-form {
  font-size: 12px;
}

.el-form-item {
  margin-bottom: 5px;
}

.age-unit {
  margin: 0 5px;
  color: #909399;
  font-size: 12px;
}

/* 强制所有模态框层级高于下拉框 */
.el-dialog__wrapper {
  z-index: 3000 !important; /* Element默认2000 */
}

/* 控制所有下拉框层级 */
.el-select-dropdown {
  z-index: 2000 !important; /* 低于模态框 */
}

.el-popper {
  z-index: 2000 !important; /* 包括Tooltip等弹出层 */
}

.no-border-select /deep/ .el-tag {
  background-color: rgba(253, 253, 253, 0.1) !important; /* 透明蓝背景 */
  border-color: rgba(64, 158, 255, 0.2) !important; /* 浅蓝色边框 */
  color: #409EFF !important; /* 蓝色文字 */
  margin: 2px 6px 2px 0 !important; /* 调整间距 */
}

/* 鼠标悬停效果 */
.no-border-select /deep/ .el-tag:hover {
  opacity: 0.8;
}

/* 移除默认的关闭按钮（如需保留可删除此部分） */
.no-border-select /deep/ .el-tag__close {
  color: #409EFF !important;
}

.no-border-select /deep/ .el-select-dropdown {
  border: none !important;
  box-shadow: none !important;
  margin-top: 0 !important; /* 移除下拉框与输入框的间距 */
}

/* 可选：移除输入框边框 */
.no-border-select /deep/ .el-input__inner {
  border: none !important;
  box-shadow: none !important;
}

/deep/ .el-dialog__header {
  padding: 10px;
  background-color: #007bb0;
}

/deep/ .el-dialog__title {
  font-size: 14px;
  color: #fff;
}

/* 面板样式 */
.keywords-panel {
  width: 100%;
  max-height: 60vh;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow-y: auto;
  padding: 10px;
}

/* 标题头 */
.keywords-header {
  padding: 5px 10px;
  font-weight: bold;
  border-bottom: 1px dashed #eee;
  margin-bottom: 10px;
  color: #1890ff;
}

/* 分组区块 */
.group-section {
  margin-bottom: 15px;
}

.group-title {
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
  padding-left: 5px;
  border-left: 3px solid #1890ff;
}

.group-keywords {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 标签样式 */
.keyword-tag {
  cursor: pointer;
  transition: all 0.2s;
}

.keyword-tag:hover {
  background: #1890ff;
  color: white;
  transform: translateY(-2px);
}

.keywords-panel {
  display: flex;
  width: 600px;
  max-height: 400px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  position: absolute;
  z-index: 9999;
}

.keywords-sidebar {
  width: 120px;
  padding: 10px 0;
  overflow-y: auto;
}

.divider {
  width: 1px;
  background: repeating-linear-gradient(#ebeef5, #ebeef5 2px, transparent 2px, transparent 4px);
  margin: 8px 0;
}

.group-title {
  padding: 8px 15px;
  cursor: pointer;
  font-size: 13px;
  color: #606266;
  transition: all 0.3s;
}

.group-title:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

.group-title.active {
  background-color: #ecf5ff;
  color: #409eff;
  font-weight: 500;
  border-right: 2px solid #409eff;
}

.keywords-content {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  gap: 8px;
}

.keyword-tag {
  cursor: pointer;
  margin: 2px;
  transition: all 0.2s;
}

.keyword-tag:hover {
  background-color: #409eff;
  color: white;
  transform: translateY(-1px);
}

.keywords-panel {
  position: absolute;
  z-index: 1000;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 10px;
  max-height: 300px;
  overflow-y: auto;
}

.keyword-tag {
  margin: 3px;
  cursor: pointer;
}

.keyword-tag:hover {
  background-color: #1890ff;
  color: white;
}

.cell-input ::v-deep .el-input__inner {
  border: none;
  background: transparent;
  color: #0c0c0c;
  font-size: 15px;
}

.cell-input ::v-deep .el-input__inner:focus {
  outline: none;
  box-shadow: none;
}

/* 确保所有描述项的标签不换行 - Vue 2 深度选择器语法 */
/deep/ .el-descriptions-item__label {
  white-space: nowrap !important;
  min-width: 80px !important;
}

/* 调整描述项内容区域的宽度，使其自适应剩余空间 */
/deep/ .el-descriptions-item__content {
  width: auto;
  flex: 1;
}


.sidebar-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止内部溢出影响外部布局 */
}

.compact-form {
  flex: 1;
  overflow-y: auto; /* 表单内容超出时显示垂直滚动条 */
  padding: 8px;
}


.el-main.content {
  // ... existing code ...
  padding: 0; /* 移除父容器内边距 */
}

.menu-item {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.menu-item:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

.menu-item i {
  margin-right: 5px;
}

.context-menu {
  position: fixed;
  z-index: 9999;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  min-width: 60px;
  max-width: 300px;
  padding: 5px 0;
}

.left-sidebar {
  background-color: transparent;
  border: 1px solid #e6e6e6;
  border-radius: 12px 0 0 12px; /* 修改：左上角和左下角12px圆角，右上角和右下角直角 */
  overflow: hidden;
  padding: 0; /* 修改：移除内边距 */
  display: flex;
  flex-direction: column;
}

.right-sidebar {
  height: 100%;
  background-color: transparent;
  border: 1px solid #e6e6e6;
  border-radius: 0 12px 12px 0; /* 修改：左上角和左下角12px圆角，右上角和右下角直角 */
  overflow: hidden;
  padding: 0; /* 修改：移除内边距 */
  display: flex;
  flex-direction: column;
}

.patient-tables {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0 !important; /* 移除内边距 */
  margin: 0;
}

/* 基础布局样式 */
.medical-workstation {
  width: 100%;
  display: flex;
  flex-direction: column;
  height: 85vh;
  overflow: hidden;
}

/* 顶部导航栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  height: 60px;
}

.header-left, .header-right {
  display: flex;
  align-items: center;
}

/* 主容器 */
.main-container {
  width: 100%;
  display: flex;
  flex: 1;
  overflow: hidden;
}


/* 患者列表区域 */
.patient-list {
  background-color: transparent;
  border-radius: 8px;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}


.table-header {
  padding: 8px 8px;
  background-color: #f0f7ff;
  border-bottom: 1px solid #e6e6e6;
  font-weight: 600;
  color: #1890ff;
  font-size: 14px;
  display: flex; /* 添加flex布局 */
  justify-content: space-between; /* 两端对齐 */
  align-items: center; /* 垂直居中 */
}

.content-header {
  background-color: #f0f7ff;
  font-weight: 600;
  color: #1890ff;
  font-size: 14px;
  width: 100%;
  margin-top: 0; /* 移除负边距 */
  box-sizing: border-box; /* 确保宽度包含内边距 */
  position: sticky; /* 粘性定位确保顶部显示 */
  top: 0;
  z-index: 1; /* 防止内容遮挡 */
  display: flex; /* 添加flex布局 */
  justify-content: space-between; /* 两端对齐 */
  align-items: center; /* 垂直居中 */
  padding: 8px 8px; /* 调整内边距 */
}

.header-content {
  display: flex; /* 标题区域flex布局 */
  align-items: center;
}

.clinic-title {
  margin-left: 20px; /* 门诊文字右移 */
  font-size: 14px;
}

.visit-count {
  margin-left: 30px; /* 就诊次数进一步右移 */
  color: #5dd94b; /* 次要信息颜色 */
  font-size: 12px;
}

.header-actions {
  display: flex; /* 按钮组flex布局 */
  gap: 8px; /* 按钮间距 */
}


.upper-table {
  flex: 4;
}

.lower-table {
  flex: 5;
}

.el-table {
  flex: 1;
  width: 100% !important;
  margin: 0;
  border-collapse: collapse;
  font-size: 13px;
}


.el-table__header-wrapper,
.el-table__body-wrapper {
  border: none;
}

/* 主内容区域 */
.content {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;
}

/* 患者基本信息 */
.patient-basic-info {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 15px;
}


/* 病历记录区域 */
.medical-record {
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border: 1px solid #e6e6e6;
}

.record-tabs {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.record-content {
  flex: 1;
  overflow-y: auto;
}

/* 诊疗方案 */
.treatment-plan {
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 15px;
  flex: 1.5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.treatment-plan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 处方预览 */
.prescription-preview {
  background-color: #fff;
  border-radius: 4px;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.prescription-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.prescription-content {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
}

/* 费用总计 */
.cost-summary {
  padding: 15px;
  border-bottom: 1px solid #e6e6e6;
}

.cost-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.cost-total {
  display: flex;
  justify-content: space-between;
  font-weight: bold;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ddd;
}

.total-value {
  color: #f56c6c;
  font-size: 18px;
}

/* 诊断结果 */
.diagnosis-result {
  padding: 15px;
  border-radius: 4px;
  flex: 1;
  overflow-y: auto;
}

.diagnosis-item {
  padding: 10px;
  background-color: #fff;
  margin-bottom: 10px;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.diagnosis-code {
  font-size: 12px;
  color: #999;
}

/* 底部工具栏 */
.bottom-tools {
  display: flex;
  padding: 10px 20px;
  background-color: #fff;
  border-top: 1px solid #e6e6e6;
  height: 50px;
}

.seedoctorMedical {
  padding: 8px 8px;
}

.seedoctorMedical ::v-deep .el-descriptions {
  margin: 2px 0 !important;
}

.seedoctorMedical ::v-deep .el-descriptions__table {
  border-radius: 6px;
  overflow: hidden;
  background-color: #fffbe6;
  width: 100%;
  border-collapse: separate; /* 关键：独立边框控制 */
  border-spacing: 0;
  font-size: 12px !important; /* 缩小字体 */
}

.seedoctorMedical ::v-deep .el-descriptions-item__cell {
  background-color: #fffbe6 !important;
  padding: 0 !important; /* 移除默认内边距 */
}

.seedoctorMedical ::v-deep .el-descriptions-item__label.is-bordered-label {
  border-color: #e6e6e6;
  width: auto; /* 固定label宽度 */
  min-width: 100px;
}

.seedoctorMedical ::v-deep .el-descriptions-item__content {
  border-color: #e6e6e6;
  width: calc(100% - 100px); /* 剩余宽度给内容区 */
}

.seedoctorMedical ::v-deep .el-descriptions-item__label.is-bordered-label {
  width: 100px;
  min-width: 100px;
  border-color: #dcdfe6;
}

.seedoctorMedical ::v-deep .el-descriptions-item__content {
  width: calc(100% - 100px);
  border-color: #dcdfe6;
}

/* 病历表头样式 */
.medical-header {
  background: white;
  border-radius: 8px 8px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid #dcdfe6;
  border-bottom: none;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.medical-header span {
  color: #1890ff;
  font-weight: bold;
}

.header-actions .el-button {
  margin-left: 10px;
}

/* 调整表格圆角 */
.seedoctorMedical ::v-deep .el-descriptions__table {
  border-radius: 0 0 8px 8px;
  border-top: none;
}

.seedoctorMedical ::v-deep .el-descriptions-item__label.is-bordered-label,
.seedoctorMedical ::v-deep .el-descriptions-item__content {
  border-color: #dcdfe6;
}

::v-deep .el-cascader .el-input__inner::placeholder {
  color: var(--el-text-color-placeholder) !important; /* 使用官方变量 */
}

</style>